local redis = require "resty.redis"
ip = "127.0.0.1"
port = g_env.db_port
db_cache = {}
setmetatable(db_cache, {__mode="kv"})
get = function()
local co = coroutine.running()
local db = db_cache[co]
if not db then
db = redis:new()
db:set_timeout(1000*60)
local ok, err = db:connect(ip, port)
assert(ok, "redis new error")
db_cache[co] = db
--print("new db: ",tostring(co), tostring(db) )
--print("db count:", tsize(db_cache), db_cache)
end
return db
end
外面直接调get就行了,做到每coroutine内复用。
在 2015年4月30日星期四 UTC+8下午3:08:53,陈立强写道:
https://github.com/openresty/lua-resty-redis/issues/33通过搜索发现网上也有人碰上类似的问题,如果这样是不是我每个模块需要连接redis的时候,都要复制一遍:
local redis = require "resty.redis"
local red = redis:new()
local host = "127.0.0.1"
local port = 6379
red:set_timeout(1000) -- 1 sec
local ok, err = red:connect(host, port)
难道没办法使代码复用了吗?