列表类型是Redis提供的又一个数据类型,它用来存储有序的字符串列表,常用的操作是向列表的两端添加元素和获取列表中的某个片段。
Redis列表类型在底层是用双端队列实现,在列表两端操作元素的时间复杂度为O(1),获取越靠近两端的元素效率越高。
常见的使用场景有:存储热点数据和实现队列。
列表类型的操作
命令
lpush key value #向列表左端添加元素
rpush key value #向列表又端添加元素
lpop key #从列表左端弹出元素
rpop key #从列表右端弹出元素
llen key #获取列表中元素的个数
lrange key start end #获取列表片段
lrem key count value #删除前count个值为value的元素
lindex key index #获取指定位置的值
lset key index value #设置指定位置的值
ltrim key start value #删除指定范围之外的元素
linsert key before|afger pivot value #在列表中找到值为pivot的元素,再根据before|after在其前后插入 value
rpoplpush source destination #从source中获取元素添加到destination中
示例
127.0.0.1:6379> lpush arr1 1
(integer) 1
127.0.0.1:6379> rpush arr1 8
(integer) 2
127.0.0.1:6379> lrange arr1 0 1
1) "1"
2) "8"
127.0.0.1:6379> lpush 4
(error) ERR wrong number of arguments for 'lpush' command
127.0.0.1:6379> lpush arr1 4
(integer) 3
127.0.0.1:6379> lpop arr1
"4"
127.0.0.1:6379> rpop arr1
"8"
127.0.0.1:6379> rpush arr1 2 3 4 5
(integer) 5
127.0.0.1:6379> lindex arr1 3
"4"
127.0.0.1:6379> lrem arr1 1 3
(integer) 1
127.0.0.1:6379> llen arr1
(integer) 4
127.0.0.1:6379> linsert arr1 BEFORE 3 10
(integer) -1
127.0.0.1:6379> llen arr1
(integer) 4
127.0.0.1:6379> linsert arr1 BEFORE 1 10
(integer) 5
127.0.0.1:6379> llen arr1
(integer) 5
127.0.0.1:6379> lset arr1 2 55
OK
127.0.0.1:6379> lindex arr1 2
"55"
127.0.0.1:6379> rpoplpush arr1 arr2
"5"
127.0.0.1:6379> rpoplpush arr1 arr2
"4"
127.0.0.1:6379> rpoplpush arr1 arr2
"55"
127.0.0.1:6379> rpoplpush arr1 arr2
"1"
127.0.0.1:6379> rpoplpush arr1 arr2
"10"
127.0.0.1:6379> llen arr2
(integer) 5
127.0.0.1:6379>
实践
1)存储文章评论
由于通常情况下被发表的评论不允许修改,并且在获取评论时也是全量的,评论列表通常是最新的排在最前面,即有序,所以使用列表类型很合适。
可以利用post:articleId:comments
来存储评论数据。
$articleId = incr post:counts
#序列化评论数据
$serializedData = seialize($author, $email, $time, $context)
#向列表中添加评论
lpush post:$articleId:comments $serializedData
#获取评论
$commontLen = llen post:$articleId:comments
$commentData = lrange post:$articleId:comments 0 $commentLen
$obj = unserialize($commentData)