openresty 如何通过连接池方式连接访问设置密码的redis,openrestyredis


redisUtil.lua

local redis = require "resty/redis"

local log = ngx.log
local ERR = ngx.ERR
local setmetatable = setmetatable

local _M = {

}

local mt = { __index = _M }

local function errlog(...)
    log(ERR, "Redis: ", ...)
end

function _M.exec(self, func)

    local red = redis:new()
    red:set_timeout(self.timeout)

    local ok, err = red:connect(self.host, self.port)
    if not ok then
        errlog("Cannot connect, host: " .. self.host .. ", port: " .. self.port)
        return nil, err
    end

    if self.password ~= '' then
         -- 请注意这里 auth 的调用过程
            local count
            count, err = red:get_reused_times()
            if 0 == count then
                ok, err = red:auth(self.password)
                if not ok then
                    ngx.say("failed to auth: ", err)
                    return
                end
           elseif err then
                ngx.say("failed to get reused times: ", err)
                return
          end
    end

    red:select(self.database)

    local res, err = func(red)
    if res then
        local ok, err = red:set_keepalive(self.max_idle_time, self.pool_size)
        if not ok then
            red:close()
        end
    end
    return res, err
end

function _M.new(opts)
    local config = opts or {}
    local self = {
        host = config.host or "127.0.0.1",
    password = config.password or '',
        port = config.port or 6379,
        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
    }
    return setmetatable(self, mt)
end

return _M

测试

location /redis { 
        default_type 'text/html'; 
        content_by_lua_file lua/api/redisController.lua; #相对于nginx安装目录 
    }
local request_method = ngx.var.request_method
local args = nil

--1、获取参数的值 获取前端提交参数
if "GET" == request_method then
    args = ngx.req.get_uri_args()
elseif "POST" == request_method then
    ngx.req.read_body()
    args = ngx.req.get_post_args()
end
local operation = args["operation"]
if operation == nil then
   operation ="set"
end
local redisUtil = require "util/redisUtil"
local red = redisUtil.new({host = "10.1.241.17",password="123#@!qwe"})
local res, err = red:exec(
    function(red)
        if operation =="get" then
        return red:get("test.lua.redis")
    else
        red:init_pipeline()
        red:set("test.lua.redis", "set ok")
        red:expire("test.lua.redis", 600)
        return red:commit_pipeline()
    end
    end
)
if not res then  
     ngx.say(operation.."操作没有返回值");
else
    ngx.say(res);
end 

参考如下资料
https://segmentfault.com/a/1190000004326029
https://segmentfault.com/a/1190000007207616
http://wiki.jikexueyuan.com/project/openresty/redis/auth_connect.html
http://jinnianshilongnian.iteye.com/blog/2187328/

相关内容

    暂无相关文章