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"


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM