init.lua

local delay = 5
local handler
handler = function (premature)
--ngx.log(ngx.ERR,"----------timer-do")
local resty_consul = require('resty.consul')
local consul = resty_consul:new({
host = "120.78.64.28",
port = 8500,
connect_timeout = (601000), -- 60s
read_timeout = (60
1000), -- 60s
})

local res, err = consul:list_keys("redis-cluster") -- Get all keys
if not res then
    ngx.log(ngx.ERR, err)
    return
end

local keys = {}
if res.status == 200 then
    keys = res.body
end
--local redis_addr = {}
local ip_addr = ''
--local ngx_re_split=require("ngx.re").split
for key, value in ipairs(keys) do
    local res, err = consul:get_key(value)
    if not res then
        ngx.log(ngx.ERR, err)
        return
    end

    if (table.getn(keys) == key) then
    	ip_addr = ip_addr..res.body[1].Value
    else
    	ip_addr = ip_addr..res.body[1].Value..','
    end
    --local ip_addr = ngx_re_split(res.body[1].Value,":")
    --redis_addr[key]={ip=ip_addr[1],port=ip_addr[2]}
    --ngx.print(res.body[1].Value) -- Key value after base64 decoding
end
ngx.shared.redis_cluster_addr:set('redis-addr',ip_addr)

end

if (0==ngx.worker.id() ) then
local ok, err = ngx.timer.at(0, handler)
if not ok then
ngx.log(ngx.ERR, "failed to create the timer: ", err)
return
end

local ok, err = ngx.timer.every(delay, handler)
if not ok then
    ngx.log(ngx.ERR, "failed to create the timer: ", err)
    return
end

end

posted on 2021-03-07 15:41  木林coder  阅读(564)  评论(0编辑  收藏  举报

导航