Redis
是一内存Key-Value
数据库, 现在一般都用它来做缓存服务.目前在一次生产环境中使用了它做业务缓存, 主要用的使用场景是: 抽奖活动, 活动中对于不同的奖项有奖品数量限制, 这就相当于是一个抢购的功能一般, 由于后端的服务是分布式的, 这便衍生出一个问题, 这个奖品数量的控制如何实现? 参考了下一些网友的经验, 发现他们大部分都是使用 Redis
的 SETNX
命令+sleep
实现类似锁的概念. 但sleep
的方法似乎会造成一些不必要的资源消耗, 官方推荐的是使用Redisson
(Java
语言), 它已经实现了RLock
, 不过我们已经使用了Jedis
实现对Redis
操作. 不知道大家对此场景有更加好的建议? 如果有使用过Redisson
和Jedis
经验最好, 可以一起分析讨论下两者的差异与优缺点.谢谢.
迷茫2017-04-24 09:12:16
The redsi used for counting should be a single point. DECR in redis is an atomic operation. After execution, check whether <0 to determine whether there is any margin;
Why use a lock? Please point out;
PHPz2017-04-24 09:12:16
Here are the Redis distributed lock strategies written by netizens
Implementing distributed locks based on Redis
Jedis does not implement distributed locks. The official introduced Ression as the recommended Java client later. If you implement it yourself, you may have many bugs. It is not recommended during the development stage. When you have time, you can take a look at the source code of Ression to implement distributed locks. , or see if you can take the source code and change it, and use Jedis for connection instead.
迷茫2017-04-24 09:12:16
Just use b(r|l)pop:
1. Pre-place an element into the list
2. Multiple clients perform brpop. Only one client gets the element (that is, gets the lock)
3. After processing Blpush the element back to the list and wait for other clients to get it
4. brpop can set a timeout
Disadvantages:
1. An element needs to be put in in advance
2. If the client exits abnormally after acquiring the lock, there will be problems