核心数据结构
string
内部sds,动态扩容。小于1M加倍扩,大于1M每次扩容1M。最大长度512M。
常用命令:
SET name value
GET name
SETNX name value
EXISTS name
DEL name
# 批量
MGET name1 name2 name3
MSET name1 value1 [name2 value2 ...]
# 过期
EXPIRE name timeout
SETEX name timeout value # set+expire
SETNX name value # 不存在创建
# 计数,value是数字,不超过signed long
>SET age 30
OK
>INCR age
31
>INCRBY age 5
36
>INCRBY age -5
31
类似的还有DECR key ,DECRBY key decrement
应用场景:
-
单值缓存
SET key value
GET key -
对象缓存
SET user:1 value(json)
MSET user:1:name 1880 user:2:name 2000
MGET user:1:name user:2:name -
分布式锁
SETNX product:10001 true // 1代表成功
SETNX product:10001 false // 0代表失败
DEL produce:10001
SET product:10001 true ex 10 nx -
计数器
INCR article:readcount:{id}
GET article:readcount:{id} -
Web集群session共享
spring session + redis实现session共享 -
分布式系统全局序列号
INCRBY orderid 1000
list
RPUSH key val1 val2 val3
LLEN key
LPOP key
RPOP key
# 下标操作
LINDEX
LRANGE
LTRIM
set
SADD key member1 [member2]
SMEMBERS key
SISMEMBER key member
SCARD key
SPOP key
zset
ZADD key score1 member1 [score2 member2]
ZRANGE key start stop [WITHSCORES]
ZREVRANGE key start stop [WITHSCORES]
ZCARD key
ZSCORE key member
ZRANK key member
ZRANGEBYSCORE key min max [WITHSCORES] [LIMIT]
ZREM key member [member ...]
hash
HSET key field val
HGET key field
HGETALL key
HLEN key
HMSET key field1 val1 [field2 value2]
HINCRBY key field increment
HKEYS key
HLEN key
- 对象缓存
HMSET user {userId}:name value [{userId}:name value ...]
HMGET user {userId}:name [{userId}:name ...]