1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| local key = KEYS[1] local capacity = tonumber(ARGV[1]) local rate = tonumber(ARGV[2]) local currentTime = tonumber(ARGV[3])
local bucket = redis.call('HMGET', key, 'tokens', 'lastTime') local tokens = capacity
if bucket[1] and bucket[2] then tokens = tonumber(bucket[1]) local lastTime = tonumber(bucket[2])
local newTokens = math.floor((currentTime - lastTime) * rate / 1000) tokens = math.min(capacity, tokens + newTokens) end
if tokens >= 1 then tokens = tokens - 1 redis.call('HSET', key, 'tokens', tokens, 'lastTime', currentTime) redis.call('EXPIRE', key, math.ceil(capacity / rate)) return true end
return false
|