List
基本的数据类型,列表
在redis里面,可以把list完成栈、队列、阻塞队列
所有的List命令都是 L 开头的
# list的操作 LPUSH RPUSH LRANGE:查看
127.0.0.1:6379> KEYS *
(empty list or set)
127.0.0.1:6379> LPUSH list one # LPUSH 将一个值或者多个值插入到list的####×××头部×××######(左)
(integer) 1
127.0.0.1:6379> LPUSH list two
(integer) 2
127.0.0.1:6379> LPUSH list three
(integer) 3
127.0.0.1:6379> LRANGE list 0 -1 # 获取具体的值--通过区间
1) "three"
2) "two"
3) "one"
127.0.0.1:6379> LRANGE list 0 1
1) "three"
2) "two"
127.0.0.1:6379> RPUSH list right # RPUSH 将一个值或者多个值插入到list的××尾部××(右)
(integer) 4
127.0.0.1:6379> LRANGE list 0 -1
1) "three"
2) "two"
3) "one"
4) "right"
# LPOP RPOP
127.0.0.1:6379> LPOP list # 移除list第一个元素
"three"
127.0.0.1:6379> RPOP list # 移除list的最后一个元素
"right"
127.0.0.1:6379> LRANGE list
(error) ERR wrong number of arguments for 'lrange' command
127.0.0.1:6379> LRANGE list 0 -1
1) "two"
2) "one"
# index 通过下标获取值
127.0.0.1:6379> LINDEX list 1
"one"
127.0.0.1:6379> LINDEX list 0
"two"
# LLEN 返回列表的长度
127.0.0.1:6379> LLEN list
(integer) 2
# 移除指定的值! lrem
127.0.0.1:6379> LPUSH list "four"
(integer) 4
127.0.0.1:6379> LPUSH list "five"
(integer) 5
127.0.0.1:6379> LPUSH list "three"
(integer) 6
127.0.0.1:6379> LPUSH list "three" "three"
(integer) 8
127.0.0.1:6379> LRANGE list 0 -1
1) "three"
2) "three"
3) "three"
4) "five"
5) "four"
6) "three"
7) "three"
8) "two"
##############
127.0.0.1:6379> LREM list 1 three # 从上往下移除一个three
(integer) 1
##############
127.0.0.1:6379> LRANGE list 0 -1
1) "three"
2) "three"
3) "five"
4) "four"
5) "three"
6) "three"
7) "two"
127.0.0.1:6379> LREM list 3 "three" # 从上往下移除三个three
(integer) 3
127.0.0.1:6379> LRANGE list 0 -1
1) "five"
2) "four"
3) "three"
4) "two"
# LTRIM 截取
127.0.0.1:6379> LTRIM list 1 2
OK
127.0.0.1:6379> LRANGE list 0 -1
1) "four"
2) "three"
# RPOPLPUSH 移除列表的最后一个元素,并添加到另一个的列表头!
127.0.0.1:6379> LRANGE list 0 -1
1) "four"
2) "three"
127.0.0.1:6379> LRANGE list1 0 -1
1) "hello4"
2) "hello3"
3) "hello2"
4) "hello1"
5) "hello"
6) "hello4"
127.0.0.1:6379> LRANGE list2 0 -1
1) "hello1"
2) "hello2"
3) "hello3"
4) "hello4"
##############
127.0.0.1:6379> RPOPLPUSH list list1
##############
"three"
127.0.0.1:6379> LRANGE list 0 -1
1) "four"
127.0.0.1:6379> LRANGE list1 0 -1
1) "three"
2) "hello4"
3) "hello3"
4) "hello2"
5) "hello1"
6) "hello"
7) "hello4"
# lset 将列表中指定的下标的值替换成另一个值
127.0.0.1:6379> LSET list 0 item # 存在的话会替换当前的值
OK
127.0.0.1:6379> LRANGE list 0 -1
1) "item"
127.0.0.1:6379> LSET list 1 item1 # 不存在的话就会报错!
(error) ERR index out of range
# Linsert 将某个具体的值插入到列表中,某个元素前面和后面
127.0.0.1:6379> LINSERT list before item other
(integer) 2
127.0.0.1:6379> LRANGE list 0 -1
1) "other"
2) "item"
127.0.0.1:6379> LINSERT list after item other1
(integer) 3
127.0.0.1:6379> LRANGE list 0 -1
1) "other"
2) "item"
3) "other1"
小结:
- 实际上是一个链表,before Node after,left 和 right都可以插入值
- 如果key存在,新增内容
- 如果key不存在,创建链表
- 如果移除所有值,就是空链表,也代表不存在!
- 在两边插入或者改动值,效率最高!中间元素,相对来说效率会低
消息排队!消息队列(LPUSH RPOP)!栈(LPUSH LPOP)