官方文档:Redis data types tutorial | Redis
目录
strings
Lists
Sets
Sorted sets
Hashes
其他
> set mykey value
ok
> get mykey
"value"
> set mykey newval nx
(nil)
> set mykey newval xx
OK
> mset a 10 b 20 c 30
OK
> mget a b c
1) "10"
2) "20"
3) "30"
> set counter 100
OK
> incr counter
(integer) 101
> incrby counter 50
(integer) 151
> decr counter
(integer) 150
> decrby counter 30
(integer) 120
注意:lrange接受两个索引,返回范围的第一个和最后一个元素。两个下标都可以为负,告诉 Redis从末尾开始计数:因此-1是列表的最后一个元素,-2是列表的倒数第二个元素。如果是正,则从头部开始计数。
> rpush mylist a b c
(integer)3
> lpush mylist 1 2 3
(integer)6
> lrange mylist 0 -1
1) "3"
2) "2"
3) "1"
4) "a"
5) "b"
6) "c"
> rpush mylist a b c
(integer) 3
> rpop mylist
"c"
> lpop mylist
"a"
> lrange mylist 0 -1
1) "b"
> rpush mylist a b c d
(integer) 4
> ltrim mylist 0 2
OK
> lrange mylist 0 -1
1) "a"
2) "b"
3) "c"
比如:tasks为空,设置阻塞5秒,且在5秒内没有给tasks列表添加新元素,结果如下
> brpop tasks 5
(nil)
(5.09s)
> sadd myset a b c
(integer) 3
> smembers myset
1) "a"
2) "c"
3) "b"
> sismember myset a
(integer) 1
> sadd seta 1 2 3 4 5
(integer) 5
> sadd setb 3 4 5 6
(integer) 4
>sinter seta setb
1) "3"
2) "4"
3) "5"
> zadd hackers 111 "Alan key"
(integer) 1
> zadd hackers 222 "Clanude Shanon"
(integer) 1
> zadd hackers 111 "Bask si"
(integer) 1
> zrange hackers 0 -1
1) "Alan key"
2) "Bask si"
3) "Clanude Shanon"
根据score
使用withscores参数也可以返回分数:
> zrange hackers 0 -1 withscores
1) "Alan key"
2) "111"
3) "Bask si"
4) "111"
5) "Clanude Shanon"
6) "222"
>zrangebyscore hackers -inf 111
1) "Alan key"
2) "Bask si"
> zremrangebyscore hackers 200 400
(integer) 1
根据lex
> zrank hackers "Bask si"
(integer) 1
> zadd hackers 0 "Alan Kay" 0 "Sophie Wilson" 0 "Richard Stallman" 0
"Anita Borg" 0 "Yukihiro Matsumoto" 0 "Hedy Lamarr" 0 "Claude Shannon"
0 "Linus Torvalds" 0 "Alan Turing"
> zrangebylex hackers [B [P
1) "Claude Shannon"
2) "Hedy Lamarr"
3) "Linus Torvalds"
> hset user:223 username martina firstName Martina lastName Elisa country GB
(integer) 4
> hget user:223 username
"martina"
> hmget user:223 username lastName
1) "martina"
2) "Elisa"
> hgetall user:223
1) "username"
2) "martina"
3) "firstName"
4) "Martina"
5) "lastName"
6) "Elisa"
7) "country"
8) "GB"
> hkeys user:223
1) "username"
2) "firstName"
3) "lastName"
4) "country"
> hvals user:223
1) "martina"
2) "Martina"
3) "Elisa"
4) "GB"
1.修改或查询key空间
exists 判断是否key存在
del 删除key
> set mykey hello
OK
> exists mykey
(integer) 1
> del mykey
(integer) 1
> exists mykey
(integer) 0
2.type 判断key的类型
> set mykey x
OK
> type mykey
string
> del mykey
(integer) 1
> type mykey
none
3.expire 设置key值得有效期(秒)
> set key some-value
OK
> expire key 5
(integer) 1
> get key (immediately)
"some-value"
> get key (after some time)
(nil)
简写
> set key some-value ex 5
ttl用来检查剩余生存时间
> ttl key
(integer) 2