Redis Note5:Redis-Key—String

Redis Note5:Redis-Key—String

1. String

默认是string类型

1.1 追加:append

# 追加 append ,如果没有添加,相当于set 127.0.0.1:6379[3]> APPEND name "Hello" (integer) 12 127.0.0.1:6379[3]> get name "henggaoHello" # 获取字符串长度STRLEN 127.0.0.1:6379[3]> STRLEN name (integer) 12 127.0.0.1:6379[3]> append sex "male" (integer) 4 127.0.0.1:6379[3]> keys * 1) "age" 2) "sex" 3) "name"

1.2 自增自减:INCR 、DECR 、INCRBY 、DECRBY

127.0.0.1:6379[3]> set views 0 OK # 自增1 INCR 127.0.0.1:6379[3]> INCR views (integer) 1 127.0.0.1:6379[3]> INCR views (integer) 2 127.0.0.1:6379[3]> get views "2" # 自减1 DECR 127.0.0.1:6379[3]> DECR views (integer) 1 127.0.0.1:6379[3]> get views "1" # 设置长,增张量INCRBY 127.0.0.1:6379[3]> INCRBY views 10 (integer) 11 127.0.0.1:6379[3]> get views "11" # 减量INCRBY 127.0.0.1:6379[3]> DECRBY views 5 (integer) 6 127.0.0.1:6379[3]> get views "6"

1.3 字符串范围:GETRANGE

127.0.0.1:6379[3]> set key1 "hello,henggao" OK 127.0.0.1:6379[3]> get key1 "hello,henggao" # 字符串范围,截取字符串【0,3】 127.0.0.1:6379[3]> GETRANGE key1 0 3 "hell" # 全部字符串 127.0.0.1:6379[3]> GETRANGE key1 0 -1 "hello,henggao"

1.4 替换:setrange

127.0.0.1:6379[3]> get key2 "abcdef" 127.0.0.1:6379[3]> setrange key2 1 xx (integer) 6 127.0.0.1:6379[3]> get key2 "axxdef"

1.5 设置过期时间:setex

# 设置key3的值为hello,30s后过期 127.0.0.1:6379[3]> setex key3 30 "hello" OK 127.0.0.1:6379[3]> ttl key3 (integer) 24 127.0.0.1:6379[3]> ttl key3 (integer) 14 127.0.0.1:6379[3]>

1.6 设置存在与不存在:setenx

# 如果不存在key4,创建key4 127.0.0.1:6379[3]> setnx key4 "redis" (integer) 1 # 如果存在key4,创建失败 127.0.0.1:6379[3]> setnx key4 "mongodb" (integer) 0 127.0.0.1:6379[3]> get key4 "redis" 127.0.0.1:6379[3]>

1.7 设置、获取多个值:mset 、mget

127.0.0.1:6379[3]> mset k1 v1 k2 v2 k3 v3 OK 127.0.0.1:6379[3]> keys * 1) "k2" 2) "k3" 3) "k1" 127.0.0.1:6379[3]> mget k1 k2 k3 1) "v1" 2) "v2" 3) "v3"

1.8 设置对象

# set user:1{name:zhangsan,age:23} 127.0.0.1:6379[3]> mset user:1:name zhangsan user:1:age 23 OK 127.0.0.1:6379[3]> mget user:1:name user:1:age 1) "zhangsan" 2) "23" 127.0.0.1

1.9 先获取在设置getset

# 不存在的值,返回nil 127.0.0.1:6379[3]> getset db redis (nil) # 如果存在,获取原来值,并设置新的值 127.0.0.1:6379[3]> getset db mongodb "redis" 127.0.0.1:6379[3]> get db "mongodb"