SET user:1 <json> MSET user:1:name the_name user1:age the_age
分布式锁
SETNX product:10003 true ex 10 nx # success return 1, or fail return 0
... # your operation
# release the lock DEL product:10003
计数器
INCR article:readcount:{article_id} GET article:readcount:{article_id}
Web集群共享session
Spring Session + Redis
分布式系统全局序列号
INCRBY order_id 1000
Scan 流式遍历
SCAN cursor <KEY RegularExpression> <Count>
cursor相当于一个下标,每次查询,scan会给出下一次开始的cursor,由此实现分批查询。
Redis Lua
Lua脚本可以一次性原子地执行多条redis语句。减少网络开销、替代Redis事务。
A Redis script is transactional by defination, so everything your can do with a Redis transaction, you can also do with a script, and usually the script will be both simpler and faster.
EVAL script numkeys key [key...] arg [arg...]
numkeys: 键名参数个数
接着可以以1为基址访问keys,如KEYS[1]
$ eval "return {KEYS[1], KEYS[2], ARGV[1], ARGV[2]}" 2 key1 key2 first second
key1 key2 first second
Jedis使用lua脚本
jedis.set("prod_stock_10016", "15"); Stringscript=""" local count = redis.call('get', KEYS[1]) local a = tonumber(count) local b = tonumber(ARGV[1]) if a >= b then redis.call('set', KEYS[1], a - b) return 1 end return 0 """