天天看點

apisix 插件實作定時任務

本文檔為個人部落格文檔系統的備份版本、作者:小遊、作者部落格:點選通路
local ngx         = ngx

local count = 1
local delay = 1
local handler

-- 插件源資料配置
local schema = {
    -- 類型
    type = "object",
    -- 插件接收的配置參數
    properties = {

    },
    minProperties = 1,
    -- 附加屬性
    additionalProperties = false,
}

-- 插件名
local plugin_name = "xiaoyou"

-- 插件的配置資訊
local _M = {
    -- 版本
    version = 0.1,
    -- 優先級
    priority = 2500,
    -- 插件的類型
    type = 'auth',
    -- 插件名字
    name = plugin_name,
    -- 插件的參數
    schema = schema,
}

-- 定時任務處理函數
handler = function (premature)
    if premature then
        return
    end
    -- 定時任務的處理邏輯
    count  = count +1
    local ok, err = ngx.timer.at(delay, handler)

    -- 重新建立定時任務
    -- ngx.timer.at 建立的回調是一次性的。如果要實作“定期”運作,需要在回調函數中重新建立 timer 才行。
    if not ok then
        ngx.log(ngx.ERR, "failed to create the timer: ", err)
        return
    end
end

-- 我們建立一個回調函數
local ok, err = ngx.timer.at(delay, handler)
if not ok then
    ngx.log(ngx.ERR, "failed to create the timer: ", err)
    return
end

-- 在balancer階段來處理請求
-- 常見的階段:init, rewrite,access,balancer,header filer,body filter 和 log 階段
function _M.access(conf, ctx)
    -- 傳回請求結果
    ngx.say(count)
end

-- 傳回插件對象
return _M
           

繼續閱讀