在 Redis 中设置计数器的预定义范围

Set a Predefined Range of a Counter in Redis

如何在设置 Redis 时预定义计数器的范围。我希望计数器有一个预定义的 MAX 和 MIN 值(特别是在我的情况下 MIN 值为 0),以便在值超过此范围时 INCR 或 DECR return 出错。我浏览了 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