在网上找了一个redis连接池的脚本,下面是脚本,但有点问题不太明白
每次用完redis都要调用一次redis_pool:close(),
里面会有ngx.ctx[redis_pool] = nil这样的代码
那我再次redis_pool:get_connect()的时候
if ngx.ctx[redis_pool] then
return true, ngx.ctx[redis_pool]
end
这几行代码是不是就没用了,因为ngx.ctx[redis_pool]一定是nil啊
而且ngx.ctx生命周期就是本次请求的
问一下,ngx.ctx[redis_pool]什么时候不是nil
module("redis_pool", package.seeall)
local redisConfig = require"config"
local redis = require("resty.redis")
local redis_pool = {}
--[[
先从连接池取连接,如果没有再建立连接.
返回:
false,出错信息.
true,redis连接
--]]
function redis_pool:get_connect()
if ngx.ctx[redis_pool] then
return true, ngx.ctx[redis_pool]
end
local client, errmsg = redis:new()
if not client then
return false, "redis.socket_failed: " .. (errmsg or "nil")
end
client:set_timeout(10000) --10秒
local result, errmsg = client:connect(redisConfig.REDIS_HOST, redisConfig.REDIS_PORT)
if not result then
return false, errmsg
end
ngx.ctx[redis_pool] = client
return true, ngx.ctx[redis_pool]
end
function redis_pool:close()
if ngx.ctx[redis_pool] then
ngx.ctx[redis_pool]:set_keepalive(60000, 300)
ngx.ctx[redis_pool] = nil
end
end
return redis_pool