function _M.add_host(version, addr, port)
local str = cache:get(version)
local map = {}
if str then
map = json.decode(str)
end
if not map[version] then
map[version] = {}
end
local host_list = map[version]
local found = false
for _, host in ipairs(host_list) do
if host.addr == addr then
if host.port ~= port then
host.port = port
end
found = true
break
end
end
if found then
ngx.log(ngx.INFO, "found, skip, addr: ", addr, ", port", port)
return
end
ngx.log(ngx.ERR, "not found, insert")
table.insert(host_list, {addr=addr, port=port})
local save_str = json.encode(map)
local ok, err = cache:safe_set(version, save_str)
if not ok then
ngx.log(ngx.ERR, "cache:safe_set failed, err: ", err, ", version: ", version, "save_str: ", save_str)
end
end
-- ARG version: 版本号
function _M.get_host(version)
local str = cache:get(version)
if not str then
return nil, "cache not exist"
end
local map = json.decode(str)
if not map[version] then
return nil, "host not exist"
end
local host_list = map[version]
if 0 == #host_list then
return nil, "host not exist"
end
local n = math.random(#host_list)
local host = host_list[n]
return host.addr, host.port
end
return _M