openresty lua-resty-redis 封装

搜了一下别人的封装代码,感觉不够优雅,主要是 set_keepalive 的调用时机不太好
我自己下面的代码是利用 coroutine, 每次当前 phase 结束后自动调用 set_keepalive

local redis = require "resty.redis"

local M = {}


local function set_keepalive(p,red,opts)
    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 -- 连接池大小 100 个
    opts.freetime = opts.freetime or 10 * 1000 -- 最大空闲时间 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
        ngx.log(ngx.ERR,"failed to select redis db: ",err
    end

    local t,err = ngx.thread.spawn(set_keepalive,coroutine.running(),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

相关文章

1.github代码实践源代码是lua脚本语言,下载th之后运行thmai...
此文为搬运帖,原帖地址https://www.cnblogs.com/zwywilliam/...
Rime输入法通过定义lua文件,可以实现获取当前时间日期的功能...
localfunctiongenerate_action(params)localscale_action=cc...
2022年1月11日13:57:45 官方:https://opm.openresty.org/官...
在Lua中的table(表),就像c#中的HashMap(哈希表),key和...