lua-resty-redis客户端链接池使用

set_keepalive

syntax: ok, err = red:set_keepalive(max_idle_timeout, pool_size)nginx

将当前redis连接放入ngx_lua cosocket连接池,能够设置链接的最大空闲时间每一个nginx工做进程的池的最大数git

若是成功返回1,若是错误返回nil,并返回错误描述github

注:这个方法用户替代close方法,调用该方法后,redis连接变为关闭状态,除connect()外,当前连接的后续操做都将返回已关闭的错误redis

get_reused_times

syntax: times, err = red:get_reused_times()socket

该方法用于返回当前链接被成功重用的次数,若是出现错误返回nil,并返回错误描述lua

若是连接不是来自连接池,此方法返回0(及连接从未被重用,及新建链接);若是来自连接池返回值始终大于0;所以该方法能够用于spa

判断当前链接是否来自链接池。rest

能正确使用连接池的redis connect 方法code

function connect(host, port, passwd)
    local red = redis:new()
    red:set_timeout(1000)
    local ok, err = red:connect(host, port)
    if not ok then
        logs.error("can't connect to redis: "..tostring(host)..":"..tostring(port)..' error: '..err )
        return nil
    end
 
    -- 若是访问redis不须要密码,这段代码能够省略
    if passwd ~= nil and passwd ~= ngx.null then
        local count, err_count = red:get_reused_times() -- 若是须要密码,来自链接池的连接不须要再进行auth验证;若是不作这个判断,链接池不起做用
        if type(count) == 'number' and count == 0 then
            local ok, err = red:auth(passwd)
            if not ok then
                logs.error("redis auth error: "..tostring(host)..":".. tostring(port)..' error: '..err )
                return nil
            end
        elseif err then
            logs.error("failed to authenticate: ", err_count)
            red:close()
            return nil
        end
    end
 
    return red
end

详细文档:https://github.com/openresty/lua-resty-redisblog

相关文章
相关标签/搜索