search

Home  >  Q&A  >  body text

像网易新闻收藏的功能,如果使用redis做缓存的话,应该如何实现?

像网易新闻收藏的功能,如果使用redis做缓存的话,应该如何实现?

迷茫迷茫2798 days ago806

reply all(4)I'll reply

  • 巴扎黑

    巴扎黑2017-04-22 09:01:31

    If the news has an ID or unique identifier. You can consider using the redis collection type. And the uniqueness of the collection prevents duplicate addition problems!
    redis.sadd('personmark:userID',newsID);//Add an element to the user collection
    redis.smembers('personmark:userID');//Get all the news IDs collected by the user at once

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-22 09:01:31

    Use sorted set zset;
    key is user ID;
    member is the unique ID of the news;
    Score is the date increment starting from a previous day (for example, starting from 2015-1-1, today's score is 155?); once you have the score, you can take it out without sorting and display it directly;
    zadd(key, score, member):Add news
    zrank(key, member): Returns according to score from small to large, that is, the collected news is sorted by date from new to old;
    zrangebyscore(key, min, max): Returns the set of scores from start to end, used to realize page turning display of news;

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-22 09:01:31

    key: news_fav_uid
    value: a collection of news IDs (array)
    where uid is the user ID.
    $news_ids = array(1024,1025,1026);
    echo json_encode($news_ids);
    No matter you are using Memcached/Redis/MySQL, you can store it like this.
    array_push pushes new collections to the end of the $news_ids array.
    If you want to sort by time, you only need json_decode to decode, array_reverse to flip the array, and then foreach to output.

    reply
    0
  • 阿神

    阿神2017-04-22 09:01:31

    The answer on the 1st floor is very good, but I just want to add that there is no need to use redis as a cache here, just use it as a data storage, because redis is also a database

    reply
    0
  • Cancelreply