乐趣区

关于openresty:openresty-redis工具类luarestyredis

个性

  • 应用连接池
  • 连贯只须要一次认证

装置

opm install openresty/lua-resty-redis

代码 redis.lua

-- redis 客户端 
local redis = require("resty/redis")
local config = {
    host = "127.0.0.1",
    port = 6379,
    password = "",
    db_index = 0,
    max_idle_time = 30000,
    database = 0,
    pool_size = 100,
    timeout = 5000,
}

local _M = {}

function _M.new()
    local instance = {
        host = config.host or "127.0.0.1",
        port = config.port or 6379,
        password = config.password or "",
        timeout = config.timeout or 5000,
        database = config.database or 0,
        max_idle_time = config.max_idle_time or 60000,
        pool_size = config.pool_size or 100
    }
    setmetatable(instance, {__index = _M})
    return instance
end

function _M:exec(func)
    local red = redis:new()
    -- 为后续操作设置超时(以毫秒为单位)爱护,包含 connect 办法。red:set_timeout(self.timeout)

    -- 建设连贯
    local ok, err = red:connect(self.host, self.port)
    if not ok then
        ngx.log(ngx.ERR, "Redis:", "Cannot connect, host:" .. self.host .. ", port:" .. self.port)
        return nil, err
    end

    if self.password ~= "" then
        -- 如果连贯来自于连接池中,get_reused_times() 永远返回一个非零的值
        -- 只有新的连贯才会进行受权
        local count, err = red:get_reused_times()
        if count == 0 then
            ok, err = red:auth(self.password)
            if not ok then
                red:close()
                return ok, err
            end
        end
    end

    if self.database ~= 0 then
        red:select(self.database)
    end

    -- 执行业务逻辑
    local res, err = func(red)
    -- 将连贯放回连接池
    local ok, err = red:set_keepalive(self.max_idle_time, self.pool_size)
    if not ok then
        red:close()
    end
    return res, err
end

return _M

理论应用

local redis = require("redis")
local red = redis.new()
local v, err = red:exec(function(red)
    return red:get("wechat:login_key")
end)

-- print(v, type(v), err, type(err))
-- v 不存在时是 UserData 类型
if not v or v == ngx.null then
    -- 解决 key 不存在状况
end
-- 解决存在状况 

参考文章

https://segmentfault.com/a/11…
https://github.com/openresty/…
https://xiaorui.cc/archives/4784
https://cloud.tencent.com/dev…

退出移动版