zoukankan      html  css  js  c++  java
  • Redis之List 列表

    Redis List 列表

    Redis列表是简单的字符串列表,按照插入顺序排序。你可以添加一个元素导列表的头部(左边)或者尾部(右边)

    一个列表最多可以包含 232 - 1 个元素 (4294967295, 每个列表超过40亿个元素)。

    应用场景:

    1.取最新N个数据的操作

    比如典型的取你网站的最新文章,通过下面方式,我们可以将最新的5000条评论的ID放在Redis的List集合中,并将超出集合部分从数据库获取

    • 使用LPUSH latest.comments命令,向list集合中插入数据
    • 插入完成后再用LTRIM latest.comments 0 5000命令使其永远只保存最近5000个ID
    • 然后我们在客户端获取某一页评论时可以用下面的逻辑(伪代码)
      FUNCTION get_latest_comments(start,num_items):
        id_list = redis.lrange("latest.comments",start,start+num_items-1)
        IF id_list.length < num_items
            id_list = SQL_DB("SELECT ... ORDER BY time LIMIT ...")
        END
        RETURN id_list
      
      如果你还有不同的筛选维度,比如某个分类的最新N条,那么你可以再建一个按此分类的List,只存ID的话,Redis是非常高效的。

    示例

    取最新N个评论的操作

    127.0.0.1:6379> lpush mycommment 100001
    (integer) 1
    127.0.0.1:6379> lpush mycommment 100002
    (integer) 2
    127.0.0.1:6379> lpush mycommment 100003
    (integer) 3
    127.0.0.1:6379> lpush mycommment 100004
    (integer) 4
    
    127.0.0.1:6379> LRANGE mycommment 0 -1
    1) "100004"
    2) "100003"
    3) "100002"
    4) "100001"
    127.0.0.1:6379> HSET comment_hash 100004 "i like peace"
    (integer) 1
    127.0.0.1:6379> hset comment_hash 100003 "go to hell"
    (integer) 1
    127.0.0.1:6379> hget comment_hash 100004
    "i like peace"
    127.0.0.1:6379> hget comment_hash 100003
    "go to hell"
  • 相关阅读:
    解决adb的"more than one device and emulator"错误
    Swoole实现简单的http服务器
    Unity实现物体位置变换
    Unity实现放大或缩小某个物体
    如何使用WEBSOCKET实现前后端通信
    实体类接收Date类型
    easyExce输出Excel只有表头没有数据问题解决
    报餐统计
    使用 EasyExcel 写Excel数据(表头动态)
    bladex分页
  • 原文地址:https://www.cnblogs.com/wzjbg/p/6597386.html
Copyright © 2011-2022 走看看