Skip to content

Instantly share code, notes, and snippets.

@leandromoreira
Last active January 26, 2019 11:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leandromoreira/b0144cde4d9a7ab38fc25c3a44305a8a to your computer and use it in GitHub Desktop.
Save leandromoreira/b0144cde4d9a7ab38fc25c3a44305a8a to your computer and use it in GitHub Desktop.
-- redis_client is an instance of a redis_client
-- key is the limit parameter, in this case ngx.var.arg_token
redis_rate.measure = function(redis_client, key)
local current_time = math.floor(ngx.now())
local current_minute = math.floor(current_time / 60) % 60
local past_minute = current_minute - 1
local current_key = key .. current_minute
local past_key = key .. past_minute
local resp, err = redis_client:get(past_key)
local last_counter = tonumber(resp)
resp, err = redis_client:incr(current_key)
local current_counter = tonumber(resp) - 1
resp, err = redis_client:expire(current_key, 2 * 60)
local current_rate = last_counter * ((60 - (current_time % 60)) / 60) + current_counter
return current_rate, nil
end
return redis_rate
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment