Reputation: 349
How do I predefine a range of a Counter in Redis while setting it up. I want the Counter to have a predefined MAX and a MIN value(specifically in my case MIN value is 0) such that INCR or DECR return an error if the value is surpassing this Range. I went through the Redis Documentation and i didn't find any answer.
Upvotes: 2
Views: 827
Reputation: 49942
Redis does not provide this built-in, but you can use it to build it yourself. There are many ways to do this, my personal preference is using Lua scripts - read EVAL
for more background.
In this case, I'd use this script:
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
Here's the output of a sample run from the command line:
$ 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
Upvotes: 2