redis 链表(list)操作

redis 链表操作

向链表添加数据

l[r]push key value[s]
例如:
lpush chars a
rpush chars b
lpush chars c d e
127.0.0.1:6379> lpush chars a
(integer) 1
127.0.0.1:6379> rpush chars b
(integer) 2
127.0.0.1:6379> rpush chars c
(integer) 3
127.0.0.1:6379> lpush chars 0
(integer) 4

查看链表数据

lrange key start stop
例如:
lrange chars 0 -1  # 查看整个链表数据
127.0.0.1:6379> lrange chars 0 -1
1) "0"
2) "a"
3) "b"
4) "c"

从链表中弹出数据

l[r]pop key
例如:
lpop chars
rpop chars
127.0.0.1:6379> lpop chars
"0"
127.0.0.1:6379> rpop chars
"c"

从链表中移除数据

lrem key num value  # num 是移除几次, value 是要移除的 值
例如:
lrem answer 2 a  # 意思是 将链表中的 a 移除 两个
lrem answer -2 a  # 意思是 反向 另一端
127.0.0.1:6379> lpush answer a b c a b d a
(integer) 7
127.0.0.1:6379> lrange answer 0 -1
1) "a"
2) "d"
3) "b"
4) "a"
5) "c"
6) "b"
7) "a"
127.0.0.1:6379> lrem answer 1 b
(integer) 1
127.0.0.1:6379> lrange answer 0 -1
1) "a"
2) "d"
3) "a"
4) "c"
5) "b"
6) "a"

127.0.0.1:6379> lrem answer -2 a
(integer) 2
127.0.0.1:6379> lrange answer 0 -1
1) "a"
2) "d"
3) "c"
4) "b"

截取链表中的一段数据

ltrim key start end
例如:
ltrim answer 0 3
127.0.0.1:6379> ltrim answer 2 4
OK
127.0.0.1:6379> lrange answer 0 -1
1) "c"
2) "b"

取出链表中某个位置的值

lindex key index
例如:
lindex answer 1
127.0.0.1:6379> lindex answer 1
"b"
127.0.0.1:6379> lindex answer 3
(nil)

查看链表长度

llen key
例如:
llen answer
127.0.0.1:6379> rpush answer a b c d
(integer) 6
127.0.0.1:6379> llen answer
(integer) 6

从一个链表中 pop 出数据 然后 push 进入另一个链表

rpoplpush source dest  # source 源链表  dest 目标链表
127.0.0.1:6379> lrange nums 0 -1
1) "1"
2) "2"
3) "3"
4) "6"
5) "8"
6) "9"
127.0.0.1:6379> rpoplpush nums answer
"9"
127.0.0.1:6379> lrange answer 0 -1
1) "9"
2) "c"
3) "b"
4) "a"
5) "b"
6) "c"
7) "d"

定值前后插入

linsert key [BEFOREafter] value1 value2
# value1 是原数值  value2 是要插入的数值
例如:
127.0.0.1:6379> rpush nums 1 3 6 8 9
(integer) 5
127.0.0.1:6379> linsert nums BEFORE 3 2
(integer) 6
127.0.0.1:6379> lrange nums 0 -1
1) "1"
2) "2"
3) "3"
4) "6"
5) "8"
6) "9"

等待 push 然后直接 pop 出去

brpop key [key2 ...] timeout  # timeout 超时 自动 pop
例如:
brpop aa bb 10
127.0.0.1:6379> brpop aa bb 10
(nil)
(10.12s)
127.0.0.1:6379> brpop job 20  # 另外开了一个终端 push 数据
1) "job"
2) "e"
(14.44s)
原文地址:https://www.cnblogs.com/sha-ka/p/12779239.html