【问题标题】:Redis increment only if < certain number?Redis仅在<特定数字时才增加?
【发布时间】: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 之后进行检查吗?

标签: ruby redis


【解决方案1】:

您可以使用WATCH/MULTI/EXEC 语义来进行乐观锁定,或者编写这样的 Lua(未测试):

local r=redis.call('GET', KEYS[1])
if r < ARGV[1] then
  redis.call('INCR', KEYS[1])
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-22
    • 1970-01-01
    • 1970-01-01
    • 2013-02-14
    • 1970-01-01
    • 2022-07-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多