如何在设置 Redis 时预定义计数器的范围。我希望计数器有一个预定义的 MAX 和 MIN 值(特别是在我的情况下 MIN 值为 0),这样如果该值超出此范围,则 INCR 或 DECR 返回错误。我浏览了 Redis 文档,但没有找到任何答案。
最佳答案
Redis 不提供此内置功能,但您可以使用它自己构建。有很多方法可以做到这一点,我个人更喜欢使用 Lua 脚本 - 阅读 EVAL
了解更多背景。
在这种情况下,我会使用这个脚本:
local val = tonumber(redis.call('GET', KEYS[1]))
if not val then
val = 0
end
local inc = val + tonumber(ARGV[1])
if inc < tonumber(ARGV[2]) or inc > tonumber(ARGV[3]) then
error('Counter is out of bounds')
else
return redis.call('SET', KEYS[1], inc)
end
以下是从命令行运行示例的输出:
$ redis-cli --eval incrbyminmax.lua foo , 5 0 10
(integer) 5
$ redis-cli --eval incrbyminmax.lua foo , 5 0 10
(integer) 10
$ redis-cli --eval incrbyminmax.lua foo , 5 0 10
(error) ERR Error running script (call to f_ada0f9d33a6278f3e55797b9b4c89d5d8a012601): @user_script:8: user_script:8: Counter is out of bounds
$ redis-cli --eval incrbyminmax.lua foo , -9 0 10
(integer) 1
$ redis-cli --eval incrbyminmax.lua foo , -9 0 10
(error) ERR Error running script (call to f_ada0f9d33a6278f3e55797b9b4c89d5d8a012601): @user_script:8: user_script:8: Counter is out of bounds
关于redis - 在 Redis 中设置计数器的预定义范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36289602/