Ruby 带有 EX 和 NX 的 REDIS

Ruby REDIS with EX AND NX

我正在尝试在我们的 rails 应用程序服务器中实施锁定。

如果我想永远获取锁,

REDIS.setnx 可以正常工作。但是我想获得过期的锁,基本上我希望锁在一定时间后过期,以便可以再次免费获得锁。

从REDIS的set documentation来看,是可以的。 https://redis.io/commands/set "The command SET resource-name anystring NX EX max-lock-time is a simple way to implement a locking system with Redis."

如何在 ruby 中实现它。 命令:

REDIS = Redis.new(host: ENV['REDIS_HOST'], port: ENV['REDIS_PORT'])
REDIS.set "key", "value", "nx", "ex", 3600

抛出错误:

ArgumentError: wrong number of arguments (given 5, expected 2..3)

还有另一种方法可以做到这一点,但它需要两次 REDIS 调用。

if(REDIS.setnx "key", "value")
    REDIS.setex "key", 3600, "value"
end

这种方法不是首选。我正在寻找一种通过 ruby 中的单个 REDIS 调用来获取 REDIS 锁的方法。基本上 "SET resource-name anystring NX EX max-lock-time" 相当于 ruby.

谢谢,

安舒尔

Redis(gem) v3.2.2 中似乎添加了这个,see PR 547。 它应该像标志一样使用,而不是作为裸字符串使用,see test.

r.set("foo", "qux", :nx => true)

这让我相信你应该能够做到这一点:

r.set("foo", "qux", :nx => true, :ex => 2.hours)