lua redis哨兵连接

2022/7/3 2:21:55

本文主要是介绍lua redis哨兵连接,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

local core = require("apisix.core")
local redis = require("resty.redis")

local config_map = {
    serv_list = {
        { ip = "xxx.xxx.xxx.xxx", port = 8001 },
        { ip = "yyy.yyy.yyy.yyy", port = 8001 },
        { ip = "zzz.zzz.zzz.zzz", port = 8001 }
    },
    possword = "xxxxxxxxx",
    timeout = 1000
}

local function redis_query_masterinfo()
    local errors = {}
    local serv_list = config_map.serv_list
    for i = 1, #serv_list do
        local ip = serv_list[i].ip
        local port = serv_list[i].port
        local red = redis:new()
        local ok, err
        red:set_timeout(config_map.timeout)
        for k = 1, DEFAULT_MAX_CONNECTION_ATTEMPTS do
            ok, err = red:connect(ip, port)
            if ok then
                break
            end
            if err then
                core.log.error("redis Cannot connect, ", string.format("host: %s,port: %s", ip, port))
                return ok, err
            end
        end
        if ok then
            local rs, err1 = red:info()
            if not rs then
                return rs, err1
            end
            local rs_li = splitStr(rs, "\n")

            local master_info
            for _, v in pairs(rs_li) do
                local iexist = string.find(v, "master%d:")
                if iexist then
                    master_info = v
                end
            end
            local st = splitStr(splitStr(master_info, ",address=")[2], ",")[1]
            local m_ipport = splitStr(st, ":")
            local master_ip = m_ipport[1]
            local master_port = m_ipport[2]
            return { master_ip, master_port }, nil
        end
    end
    return nil, errors
end

local function redis_query_key(key)
    local master_info, err = redis_query_masterinfo()
    if not master_info then
        return nil, err
    end
    local master_ip = master_info[1]
    local master_port = master_info[2]
    local red = redis:new()
    red:set_timeout(config_map.timeout)
    local ok, err = red:connect(master_ip, master_port)
    if not ok then
        core.log.error("redis Cannot connect, ", string.format("host: %s,port: %s", master_ip, master_port))
        return ok, err
    end
    --密码和选择的桶
    local res, err = red:auth(config_map.possword)
    if not res then
        core.log.error("redis failed to authenticate: ", err)
        return res, err
    end
    red:select(0)
    local val = red:get(key)
    return val, nil
end

 



这篇关于lua redis哨兵连接的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程