redis常用命令
[root@liu ~]# redis-cli -p 6379
127.0.0.1:6379> keys * #查询所有key
1) "key:__rand_int__"
2) "myhash"
3) "name"
4) "counter:__rand_int__"
5) "mylist"
127.0.0.1:6379> flushall #删除所有键
OK
127.0.0.1:6379> keys *
(empty array)
127.0.0.1:6379> set name liu #插入键
OK
127.0.0.1:6379> exists name #查询键是否存在
(integer) 1
127.0.0.1:6379> expire name 10 #设置存留时间
(integer) 1
127.0.0.1:6379> ttl name #查看剩余存留时间
(integer) 6
127.0.0.1:6379> ttl name
(integer) 3
127.0.0.1:6379> ttl name
(integer) -2
127.0.0.1:6379> exists name
(integer) 0
127.0.0.1:6379> get name
(nil)
127.0.0.1:6379> set name liu
OK
127.0.0.1:6379> type name #查询键的类型
string
127.0.0.1:6379>
String 常用命令
字符串的添加
127.0.0.1:6379> flushdb #清除当前键
OK
127.0.0.1:6379> keys *
(empty array)
127.0.0.1:6379> set ky1 liu
OK
127.0.0.1:6379> get key1
(nil)
127.0.0.1:6379> get ky1
"liu"
127.0.0.1:6379> append ky1 hello #追加字符
(integer) 8
127.0.0.1:6379> strlen ky1 #查询字符的长度
(integer) 8
127.0.0.1:6379> get ky1
"liuhello"
127.0.0.1:6379> append key1 liu #如果key不存在,相当于set key
(integer) 3
127.0.0.1:6379> keys *
1) "ky1"
2) "key1"
字符串的自增自减
127.0.0.1:6379> set views 0
OK
127.0.0.1:6379> incr view #自增
(integer) 1
127.0.0.1:6379> get ciew
(nil)
127.0.0.1:6379> get views
"0"
127.0.0.1:6379> get view
"1"
127.0.0.1:6379> decr view #自减
(integer) 0
127.0.0.1:6379> get view
"0"
127.0.0.1:6379> incrby view 10 #自增一定长度
(integer) 10
127.0.0.1:6379> get view
"10"
127.0.0.1:6379> decrby views 10 #自减一定长度
(integer) -10
127.0.0.1:6379> get view
"10"
127.0.0.1:6379> get views
"-10"
字符串范围
127.0.0.1:6379> get ky1
"liuhello"
127.0.0.1:6379> getrange ky1 0 7 #取[0,7]字符串
"liuhello"
127.0.0.1:6379> getrange ky1 0 3
"liuh"
127.0.0.1:6379> setrange ky1 3 XXX #修改1以后的字符串
(integer) 8
127.0.0.1:6379> get ky1
"liuXXXlo"
设置set过期时间
setex (set with expire) # 设置过期时间
setnx (set if not exist) # 不存在在设置(在分布式锁中会常常使用!)
ttl key # 查看过期时间
127.0.0.1:6379> SETEX key1 10 lisen # key1 的值为 lisen,10秒后过期
OK
127 .0.0.1:6379> setnx mykey "redis" # 如果mykey 不存在,创建mykey
批量操作set get
# 同时设置多个值
# mset
127.0.0.1:6379> mset k1 v1 k2 v2 k3 v3
OK
127.0.0.1:6379> keys *
1) "view"
2) "k3"
3) "k2"
4) "k1"
# 同时获取多个值
# mget
127 .0.0.1:6379> mget k1 k2 k3
1 ) "v1"
2 ) "v2"
3 ) "v3"