技术开发 频道

Redis详解:lists数据类型及操作

  6、ltrim

  保留指定key 的值范围内的数据:

redis 127.0.0.1:6379> rpush mylist8 "one"
(
integer) 1
redis
127.0.0.1:6379> rpush mylist8 "two"
(
integer) 2
redis
127.0.0.1:6379> rpush mylist8 "three"
(
integer) 3
redis
127.0.0.1:6379> rpush mylist8 "four"
(
integer) 4
redis
127.0.0.1:6379> ltrim mylist8 1 -1
OK
redis
127.0.0.1:6379> lrange mylist8 0 -1
1) "two"
2) "three"
3) "four"
redis
127.0.0.1:6379>

  7、lpop

  从list的头部删除元素,并返回删除元素:

redis 127.0.0.1:6379> lrange mylist 0 -1
1) "hello"
2) "world"
redis
127.0.0.1:6379> lpop mylist
"hello"
redis
127.0.0.1:6379> lrange mylist 0 -1
1) "world"
redis
127.0.0.1:6379>

  8、rpop

  从list的尾部删除元素,并返回删除元素:

redis 127.0.0.1:6379> lrange mylist2 0 -1
1) "hello"
2) "world"
redis
127.0.0.1:6379> rpop mylist2
"world"
redis
127.0.0.1:6379> lrange mylist2 0 -1
1) "hello"
redis
127.0.0.1:6379>

  9、rpoplpush

  从第一个list的尾部移除元素并添加到第二个list的头部,最后返回被移除的元素值,整个操作是原子的.如果第一个list是空或者不存在返回nil:

redis 127.0.0.1:6379> lrange mylist5 0 -1
1) "three"
2) "foo"
3) "hello"
redis
127.0.0.1:6379> lrange mylist6 0 -1
1) "hello"
2) "foo"
redis
127.0.0.1:6379> rpoplpush mylist5 mylist6
"hello"
redis
127.0.0.1:6379> lrange mylist5 0 -1
1) "three"
2) "foo"
redis
127.0.0.1:6379> lrange mylist6 0 -1
1) "hello"
2) "hello"
3) "foo"
redis
127.0.0.1:6379>

  10、lindex

  返回名称为key的list中index位置的元素:

redis 127.0.0.1:6379> lrange mylist5 0 -1
1) "three"
2) "foo"
redis
127.0.0.1:6379> lindex mylist5 0
"three"
redis
127.0.0.1:6379> lindex mylist5 1
"foo"
redis
127.0.0.1:6379>

  11、llen

  返回key对应list的长度:

redis 127.0.0.1:6379> llen mylist5
(
integer) 2
redis
127.0.0.1:6379>
2
相关文章