Redis的String数据类型及常用命令
String 字符串
字符串追加,如果没有对应的key则相当于set key
127.0.0.1:6379[1]> set key1 v1 OK 127.0.0.1:6379[1]> APPEND key1 "v1v1" (integer) 6 127.0.0.1:6379[1]> get key1 "v1v1v1"
查看字符串长度
127.0.0.1:6379[1]> STRLEN key1 (integer) 6
自增 i++
127.0.0.1:6379[1]> set age 0 OK 127.0.0.1:6379[1]> INCR age (integer) 1 127.0.0.1:6379[1]> INCR age (integer) 2 127.0.0.1:6379[1]> get age "2"
自减 i--
127.0.0.1:6379[1]> DECR age (integer) 1 127.0.0.1:6379[1]> get age "1"
自增量 i+=
127.0.0.1:6379[1]> get age "1" 127.0.0.1:6379[1]> INCRBY age 25 (integer) 26 127.0.0.1:6379[1]> get age "26"
自减量 i-=
127.0.0.1:6379[1]> get age "26" 127.0.0.1:6379[1]> DECRBY age 10 (integer) 16 127.0.0.1:6379[1]> get age "16"
获取区间的字符串 ,下标从0开始
127.0.0.1:6379[1]> set name "shangguanyu" OK 127.0.0.1:6379[1]> get name "shangguanyu" 127.0.0.1:6379[1]> GETRANGE name 0 5 "shangg" #查看全部字符串 127.0.0.1:6379[1]> GETRANGE name 0 -1 "shangguanyu"
替换指定位置的字符串
127.0.0.1:6379[1]> set key2 abcdefg OK 127.0.0.1:6379[1]> get key2 "abcdefg" 127.0.0.1:6379[1]> SETRANGE key2 2 xx (integer) 7 127.0.0.1:6379[1]> get key2 "abxxefg"
setex,setnx设置值
# setex (set with expire) #创建并设置过期时间 127.0.0.1:6379[1]> setex name 30 hello OK 127.0.0.1:6379[1]> ttl name (integer) 22 127.0.0.1:6379[1]> get name "hello" #在分布式锁的时候可以用到 # setnx (set if not exist) #不存在再创建 127.0.0.1:6379[1]> setnx mykey redis (integer) 1 127.0.0.1:6379[1]> setnx mykey mk #创建失败返回0 (integer) 0 127.0.0.1:6379[1]> get mykey "redis"
mest设置多个值用空格分隔
127.0.0.1:6379[1]> mset k1 v1 k2 v2 k3 v3 OK 127.0.0.1:6379[1]> get k1 "v1" 127.0.0.1:6379[1]> get k2 "v2" 127.0.0.1:6379[1]> get k3 "v3"
mget获取多个值
127.0.0.1:6379[1]> mget k1 k2 k3 1) "v1" 2) "v2" 3) "v3"
msetnx和setnx的性质差不多
#创建失败,因为这是原子性操作k1存在 127.0.0.1:6379[1]> msetnx k1 v1 k4 v4 (integer) 0 127.0.0.1:6379[1]> get k4 (nil) #创建成功 127.0.0.1:6379[1]> mget k1 k2 k3 k4 k5 1) "v1" 2) "v2" 3) "v3" 4) "v4" 5) "v5"
getset 先get值后set值
127.0.0.1:6379[1]> getset db redis #最开始没有值 (nil) 127.0.0.1:6379[1]> get db "redis" 127.0.0.1:6379[1]> getset db mongdb #db设置之前的值为“redis” "redis" 127.0.0.1:6379[1]> get db "mongdb"
对象设置值
127.0.0.1:6379[1]> mset user:1:name zhangsan user:1:age 18 OK 127.0.0.1:6379[1]> mget user:1:name user:1:age 1) "zhangsan" 2) "18"
**学习参考狂神学java**