【轉載請註明出處】:https://www.jianshu.com/p/cae825afaf3fui
Lua 代碼:lua
local locks = require "resty.lock" local function acquire() local lock =locks:new("locks") local elapsed, err =lock:lock("limit_key") --互斥鎖 local limit_counter =ngx.shared.limit_counter --計數器 local key = "ip:" ..os.time() local limit = 5 --限流大小 local current =limit_counter:get(key) if current ~= nil and current + 1> limit then --若是超出限流大小 lock:unlock() return 0 end if current == nil then limit_counter:set(key, 1, 1) --第一次須要設置過時時間,設置key的值爲1,過時時間爲1秒 else limit_counter:incr(key, 1) --第二次開始加1便可 end lock:unlock() return 1 end ngx.print(acquire())
Nginxspa
http { …… lua_shared_dict locks 10m; lua_shared_dict limit_counter 10m; }
【轉載請註明出處】: https://www.jianshu.com/p/cae825afaf3frest