local _M = {}
local redis = require "resty.redis"
function _M.executor(lambda, conf)
local state, db = self.connect(conf)
if state == false then
return state, 50000
end
local ret, code, data = lambda(db)
self.close_connection(db)
return ret, code, data
end
function _M.close_connection(db)
if self.ping(db) then --检测连接的状态
local ok, er = db:set_keepalive(10000, 100)
if not ok then
--log("failed to set keepalive: ", er)
end
end
end
function _M.ping(db)
local res, err = db:ping()
if not res then
--log("ping: ", err)
return false
end
return true
end
function _M.connect(conf)
local red = redis:new()
red:set_timeout(1000) -- 1 sec
local ok, err = red:connect(conf)
if not ok then
--log("failed to connect: ", err)
return false
end
return true, red
end
return _M
local redis = require('library.redis')
local ret, code, data = redis.executor(function(red)
local ok, err = red:get('a')
if not ok then
--log("failed to get a: ", err)
return false, nil
end
return true, ok
end)
if ret == true then
ngx.print(data)
end
请问如果 red:get('a') 的 ok 是nil, 那么我通过ping来测试这条连接的状态,这样方式规避状态不明的连接,是否正确呢?