Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
if not redis.pcall('exists', KEYS[1]) then
return 1
end
local bucket_name = KEYS[1]
local current_time = ARGV[1]
-- bucket {rate, timespan, last_check, tokens}
local rate = redis.pcall('hget', bucket_name, 'rate')
local timespan = redis.pcall('hget', bucket_name, 'timespan')
local last_check = redis.pcall('hget', bucket_name, 'last_check')
local tokens = redis.pcall('hget', bucket_name, 'tokens')
local time_passed = current_time - last_checked
redis.pcall('hset', bucket_name, 'last_checked', current_time)
tokens = tokens + time_passed * (rate / timespan)
if tokens > rate then
tokens = rate
end
local allow = 0
if tokens > 1.0 then
allow = 1
tokens = tokens - 1
end
redis.pcall('hset', bucket_name, 'tokens', tokens)
return allow
if redis.pcall('exists', KEYS[1]) == 0 then
return 1
end
local bucket_name = KEYS[1]
local current_time = ARGV[1]
-- bucket {rate, timespan, last_check, tokens}
local rate = redis.pcall('hget', bucket_name, 'rate')
local timespan = redis.pcall('hget', bucket_name, 'timespan')
local last_check = redis.pcall('hget', bucket_name, 'last_check')
local tokens = redis.pcall('hget', bucket_name, 'tokens')
local time_passed = current_time - last_check
redis.pcall('hset', bucket_name, 'last_checked', current_time)
tokens = tokens + time_passed * (rate / timespan)
if tokens - rate > 0 then
tokens = rate
end
local allow = 0
if tokens - 1.0 > 0 then
allow = 1
tokens = tokens - 1
end
redis.pcall('hset', bucket_name, 'tokens', tokens)
return allow
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.