OpenResty Lua-Resty-Redis Package

I searched for other people’s package code, and it feels not elegant enough, mainly because the timing of calling set_keepalive is not good.
The code below myself uses coroutine, and set_keepalive is automatically called every time the current phase ends.

p>

local redis = require "resty.redis"

local M = {}


local function set_keepalive(p, red, opts)< br /> while true do
if'dead' == coroutine.status(p) then
break
end
ngx.sleep(0.01)
end

ok, err = red:set_keepalive(opts.freetime, opts.poolsize)
if not ok then
ngx.log(ngx.ERR, "failed to set keepalive: ", err)
return
end
end

function M:new(opts)
opts = opts or {}
opts.ip = opts.ip or '127.0.0.1'
opts.port = opts.port or 6379
opts.db = opts.db or 0
opts.timeout = opts.timeout or 1000
opts.poolsize = opts.poolsize or 100 - connection pool size 100
opts.freetime = opts.freetime or 10 * 1000 - maximum idle time 10s

local red = redis:new()
red:set_ timeout(opts.timeout)

local ok, err = red:connect(opts.ip, opts.port)
if not ok then
ngx.log(ngx.ERR , "failed to connect redis: ", err)
return ok, err
end

- local count, err = red:get_reused_times()
- ngx.log(ngx.ERR, "redis get_reused_times: ", count)


local ok, err = red:select(opts.db)
if not ok then< br /> ngx.log(ngx.ERR, "failed to select redis db: ", err)
return ok, err
end

local t, err = ngx. thread.spawn(set_keepalive, coroutine.running(), red, opts)
if not t then
ngx.log(ngx.ERR, "failed to spawn thread set_keepalive: ", err)
return t, err
end

return red
end

return M

Leave a Comment

Your email address will not be published.