Skip to content

Instantly share code, notes, and snippets.

@luoyjx
Last active December 24, 2019 12:51
Show Gist options
  • Save luoyjx/6570f8857c4618f9302c4bf6ae03d713 to your computer and use it in GitHub Desktop.
Save luoyjx/6570f8857c4618f9302c4bf6ae03d713 to your computer and use it in GitHub Desktop.
-- 操作的Redis Key
local rate_limit_key = KEYS[1]
-- 每秒最大的QPS许可数
local max_permits = ARGV[1]
-- 此次申请的许可数
local incr_by_count_str = ARGV[2]
-- 当前已用的许可数
local currentStr = redis.call('get', rate_limit_key)
local current = 0
if currentStr then
current = tonumber(currentStr)
end
-- 剩余可分发的许可数
local remain_permits = tonumber(max_permits) - current
local incr_by_count = tonumber(incr_by_count_str)
-- 如果可分发的许可数小于申请的许可数,只能申请到可分发的许可数
if remain_permits < incr_by_count then
incr_by_count = remain_permitsend
-- 将此次实际申请的许可数加到Redis Key里面
local result = redis.call('incrby', rate_limit_key, incr_by_count)
-- 初次操作Redis Key设置1秒的过期
if result == incr_by_count then
redis.call('expire', rate_limit_key, 1)
end
-- 返回实际申请到的许可数
return incr_by_co
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment