1. string字符串类型的操作:
1.1. set 设置单个值
语法:set key value [EX seconds] [PX milliseconds] [NX|XX]
注:
EX seconds 设置key的生命周期(有效期)(以秒数为单位)
PX milliseconds 表示key的生命周期(有效期)(以毫秒为单位)
NX (not exists)表示key不存在时设置
XX 表示key已存在时才设置
例:
127.0.0.1:6379> set name 'wang' ex 15
OK
127.0.0.1:6379> ttl name
(integer) 13
127.0.0.1:6379> ttl name
(integer) 10
127.0.0.1:6379> set name 'yang' px 3000
OK
127.0.0.1:6379> ttl name
(integer) -2
127.0.0.1:6379> ttl name
(integer) -1
127.0.0.1:6379> set name 'zhao' ex 20
OK
127.0.0.1:6379> ttl name
(integer) 17
127.0.0.1:6379> set animal 'cat'
OK
127.0.0.1:6379> ttl animal
(integer) -1
127.0.0.1:6379> set animal 'dog' nx
(nil)
127.0.0.1:6379> set animal 'dog' xx
OK
127.0.0.1:6379>
注:ex、px不能同时写
127.0.0.1:6379> set animal cat ex 10 px 7000
(error) ERR syntax error
1.2. mset 设置多个值
语法:mset key value [key value ...]
例:
127.0.0.1:6379> mset a apple b banana c crow d dog
OK
127.0.0.1:6379> keys *
1) "c"
2) "a"
3) "animal"
4) "b"
5) "d"
1.3. get 获取单个值
语法:get key
例:
127.0.0.1:6379> mset a apple b banana c crow d dog
OK
127.0.0.1:6379> get a
"apple"
127.0.0.1:6379> get b
"banana"
1.4. mget 获取多个值
语法:mget key [key ...]
例:
127.0.0.1:6379> mset a apple b banana c crow d dog
OK
127.0.0.1:6379> mget a b d
1) "apple"
2) "banana"
3) "dog"
1.5. setrange key offset value
语法:setrange key offset value
作用:把key的值偏移量offset,开始替换为value
注:
Offset 是偏移量,可以大于key的最大长度(
例:
127.0.0.1:6379> set word hello
OK
127.0.0.1:6379> get word
"hello"
127.0.0.1:6379> setrange word 2 ??
(integer) 5
127.0.0.1:6379> get word
"he??o"
1.6. getrange key start end 获取key的指定范围的字符
语法:getrange key start end
作用:获取字符串中[start,end]范围的值
注:
start 开始索引号 (从0开始,闭区间);如果start大于end
end 结束索引号 (到end结束,闭区间,右数从-1开始)
Start>=length,返回空字符串
end>=length,截取至字符结尾
如果start所处位置在end右边,返回空字符
例:
127.0.0.1:6379> set fruit orange
OK
127.0.0.1:6379> get fruit
"orange"
127.0.0.1:6379> getrange fruit 1 4
"rang"
127.0.0.1:6379> set status working
OK
127.0.0.1:6379> getrange status 0 -3
"worki"
127.0.0.1:6379> getrange status 0 -4
"work"
1.7. getset key newvalue
语法:getset key value
作用:获取并返回旧值,设置新值
127.0.0.1:6379> set fruit orange
OK
127.0.0.1:6379> get fruit
"orange"
127.0.0.1:6379> getset fruit apple
"orange"
127.0.0.1:6379> get fruit
"apple"
127.0.0.1:6379> getset fruit 'banana'
"apple"
1.8. incr 键值(key)增加1
语法:incr key
注:
不存在的key当成0,再incr操作
范围为64有符号
例:
127.0.0.1:6379> set age 20
OK
127.0.0.1:6379> incr age
(integer) 21
1.9. incrby key number 增加自定义的数
语法:incrby key increment
例:
127.0.0.1:6379> incrby age 5
(integer) 25
1.10. incrbyfloat key floatnumber 增加一个浮点数
语法:incrbyfloat key increment
例:
127.0.0.1:6379> set score 80
OK
127.0.0.1:6379> get score
"80"
127.0.0.1:6379> incrbyfloat score 3.5
"83.5"
127.0.0.1:6379> get score
"83.5"