limit_common_flow.lua
892 Bytes
local rateLimit ={}
function rateLimit.limit_flow(limit_key,max_limit,seconds)
if not limit_key or not max_limit then
return true
end
local redises=lua_context["redises"]
local redis_util=redises[math.random(#redises)]
local redis=redis_util:getConnect()
if not redis then
return true
end
local limit=0
if seconds then
limit=redis:eval("local current;current=redis.call('incr',KEYS[1]);if tonumber(current) == 1 then redis.call('expire',KEYS[1],KEYS[2]) end return current",2,limit_key,seconds)
else
limit=redis:eval("local current;current=redis.call('incr',KEYS[1]);if tonumber(current) == 1 then redis.call('expire',KEYS[1],2) end return current",1,limit_key)
end
redis_util:close(redis)
if limit then
if tonumber(limit)>max_limit then
return false
else
return true
end
end
return true
end
return rateLimit