gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 10:58:03 24 4
gpt4 key购买 nike

如何在设置 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com