Last active
June 12, 2017 22:56
-
-
Save vseryakov/da179d7a59c7dee61712 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local name = KEYS[1]; | |
local rate = tonumber(KEYS[2]); | |
local max = tonumber(KEYS[3]); | |
local interval = tonumber(KEYS[4]); | |
local now = tonumber(KEYS[5]); | |
local count = tonumber(redis.call('HGET', name, 'count')); | |
local mtime = tonumber(redis.call('HGET', name, 'mtime')); | |
if not mtime then | |
count = max; | |
mtime = now; | |
end | |
if now < mtime then | |
mtime = now - interval; | |
end | |
if count < max then | |
count = math.min(max, count + rate * ((now - mtime) / interval)); | |
redis.call('HSET', name, 'count', count); | |
end | |
redis.call('HSET', name, 'mtime', now); | |
if count < 1 then | |
return 0; | |
else | |
redis.call('HSET', name, 'count', count - 1); | |
return 1; | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Testing:
for d in 1 2 3 4 5; do redis-cli --eval rate.lua b 3 3 1000 $(node -e 'console.log(Date.now())'); done