Redis List 列表
Redis列表是簡單的字符串列表,按照插入順序排序。你可以添加一個元素導列表的頭部(左邊)或者尾部(右邊)
一個列表最多可以包含 232 - 1 個元素 (4294967295, 每個列表超過40億個元素)。
應用場景:
1.取最新N個數據的操作
比如典型的取你網站的最新文章,通過下面方式,我們可以將最新的5000條評論的ID放在Redis的List集合中,並將超出集合部分從數據庫獲取
- 使用LPUSH latest.comments命令,向list集合中插入數據
- 插入完成后再用LTRIM latest.comments 0 5000命令使其永遠只保存最近5000個ID
- 然后我們在客戶端獲取某一頁評論時可以用下面的邏輯(偽代碼)
如果你還有不同的篩選維度,比如某個分類的最新N條,那么你可以再建一個按此分類的List,只存ID的話,Redis是非常高效的。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個評論的操作
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"