set_keepalive
syntax: ok, err = red:set_keepalive(max_idle_timeout, pool_size)
將當前redis鏈接放入ngx_lua cosocket鏈接池,可以設置連接的最大空閑時間和每個nginx工作進程的池的最大數
如果成功返回1,如果錯誤返回nil,並返回錯誤描述
注:這個方法用戶替代close方法,調用該方法后,redis鏈接變為關閉狀態,除connect()外,當前鏈接的后續操作都將返回已關閉的錯誤
get_reused_times
syntax: times, err = red:get_reused_times()
該方法用於返回當前連接被成功重用的次數,如果出現錯誤返回nil,並返回錯誤描述
如果鏈接不是來自鏈接池,此方法返回0(及鏈接從未被重用,及新建連接);如果來自鏈接池返回值始終大於0;因此該方法可以用於
判斷當前連接是否來自連接池。
能正確使用鏈接池的redis connect 方法
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