Openresty接続プールでパスワード設定のredisにアクセスする方法


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/