【发布时间】:2016-12-05 19:22:04
【问题描述】:
如何在键上调用 .incr 并使其仅在结果数字小于某个数字时才递增,而无需事先调用 .get?
事先调用 .get 的原因是有问题的,因为如果我有多个线程。可能有 100 个线程执行了下面的第一行,它们都得到值“0”,因此,所有线程都递增。如果你愿意的话,一个竞争条件。
currentVal = $redis.get('key') #all threads could be done executing this but not yet the below if condition.
if(currentVal < 3)
$redis.incr('key') #1
end
【问题讨论】:
-
我之前尝试过这样做,唯一可行的方法是使用 Lua 脚本。你可以申请类似
INCRBYTOMAX的命令。 -
如果 currentVal 是硬编码的,你不能在
incr然后decr之后进行检查吗?