Redis对链表(linked-list)结构的支持使得它在键值存储的世界中独树一帜。一个列表结构可以有序的存储多个字符串Redis列表可执行的操作和很多编程语言里面的列表操作非常相似:
LPUSH命令和RPUSH命令分别用于将元素推入列表的左端(left end)和右端(right end);
redis 127.0.0.1:6379> RPUSH mylist "hello"
(integer) 1
redis 127.0.0.1:6379> RPUSH mylist "foo"
(integer) 2
redis 127.0.0.1:6379> RPUSH mylist "bar"
(integer) 3
redis 127.0.0.1:6379> LRANGE mylist 0 -1
1) "hello"
2) "foo"
3) "bar"
redis 127.0.0.1:6379> LPUSH list1 "foo"
(integer) 1
redis 127.0.0.1:6379> LPUSH list1 "bar"
(integer) 2
redis 127.0.0.1:6379> LRANGE list1 0 -1
1) "foo"
2) "bar
LPOP命令和RPOP命令分别用于从列表的左端和右端弹出元素;
redis 127.0.0.1:6379> RPUSH list1 "foo"
(integer) 1
redis 127.0.0.1:6379> RPUSH list1 "bar"
(integer) 2
redis 127.0.0.1:6379> LPOP list1
"foo"
redis 127.0.0.1:6379> RPUSH mylist "hello"
(integer) 1
redis 127.0.0.1:6379> RPUSH mylist "hello"
(integer) 2
redis 127.0.0.1:6379> RPUSH mylist "foo"
(integer) 3
redis 127.0.0.1:6379> RPUSH mylist "bar"
(integer) 4
redis 127.0.0.1:6379> RPOP mylist
OK
redis 127.0.0.1:6379> LRANGE mylist 0 -1
1) "hello"
2) "hello"
3) "foo"
LINDEX命令用于获取列表在给定位置上的一个元素;
redis 127.0.0.1:6379> LPUSH mylist "World"
(integer) 1
redis 127.0.0.1:6379> LPUSH mylist "Hello"
(integer) 2
redis 127.0.0.1:6379> LINDEX mylist 0
"Hello"
redis 127.0.0.1:6379> LINDEX mylist -1
"World"
redis 127.0.0.1:6379> LINDEX mylist 3 # index不在 mylist 的区间范围内
(nil)
LRANGE命令用于获取列表在给定范围上的所有元素。
redis 127.0.0.1:6379> LPUSH list1 "foo"
(integer) 1
redis 127.0.0.1:6379> LPUSH list1 "bar"
(integer) 2
redis 127.0.0.1:6379> LPUSHX list1 "bar"
(integer) 0
redis 127.0.0.1:6379> LRANGE list1 0 -1
1) "foo"
2) "bar"
3) "bar"
LTRIM对列表进行修剪。
redis 127.0.0.1:6379> RPUSH mylist "hello"
(integer) 1
redis 127.0.0.1:6379> RPUSH mylist "hello"
(integer) 2
redis 127.0.0.1:6379> RPUSH mylist "foo"
(integer) 3
redis 127.0.0.1:6379> RPUSH mylist "bar"
(integer) 4
redis 127.0.0.1:6379> LTRIM mylist 1 -1
OK
redis 127.0.0.1:6379> LRANGE mylist 0 -1
1) "hello"
2) "foo"
3) "bar"