開發與維運

分佈式限流之Nginx+Lua實現

【轉載請註明出處】:https://developer.aliyun.com/article/758600

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())

Nginx

http {

    ……
    lua_shared_dict locks 10m;
    lua_shared_dict limit_counter 10m;

}

【轉載請註明出處】: https://developer.aliyun.com/article/758600

Leave a Reply

Your email address will not be published. Required fields are marked *