列表类型(list)可以存储一个有序的字符串列表,内部实现是双向链表, 借助列表类型,Redis还可以作为队列使用, 且与散列类型键最多能容纳的字段数量相同, 一个列表类型键最多能容纳2^32-1个元素
常用命令
向左向右插入元素
lpush key value [value....] 从左边向列表增加元素 rpush key value [value....] 从右边向列表增加元素 lpush numbers 1 lpush numbers 2 3 此时为 3 2 1 rpush numbers 0 rpush numbers -1 此时为 3 2 1 0 -1
从左从右弹出元素(返回元素的值)
lpop key 从左弹出 rpop key 从右弹出 此时列表numbers为 3 2 1 0 -1 lpop numbers "3" rpop numbers "-1"
一些其他的用法1
获得列表中元素的个数: llen key llen number 3 获得列表片段: lrange key start stop lrange number 0 2 1) "2" 2) "1" 3) "0" 此命令也支持负索引 lrange number -2 -1 1) "1" 2) "0" 表示右边第二个元素到右边第一个元素 若要展示number全部存储的字符串并且不知道数量 lrange number 0 -1 删除列表指定的值: lrem key count value 若列表为 2 1 0 2 lrem numbers -1 2 : 删除从右边开始的第一个2 lrange number 0 -1 1) "2" 2) "1" 3) "0"
获得/设置 指定索引的元素值
获得/设置 指定索引的元素值
lindex key index lset key index value 对于number ["2", "1", "0"] lindex number 0 "2" 获得从左开始第一个数字 lindex number -1 "0" 获得从右开始第一个数字 lset number 1 7 [2,1,0] 变为 [2,7,0] 将索引为1的值改为"7"
保留指定片段
ltrim key start end 可以删除指定索引范围之外的所有元素,索引指定范围与lrange一样 number[1,2,7,3] ltrim number 1 2 1,2 是 "2","7" 删除索引范围外的 所以为"2" "7"
插入元素
linsert key before|after pivot value 从左到右查找值为pivot的元素,然后根据bofore|after考虑将元素插在 前面还是后面 number [2, 7, 0] linset number after 7 3 number [2, 7, 3, 0]