zoukankan      html  css  js  c++  java
  • REDIS工具类

    ocal 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
  • 相关阅读:
    日积月累--小技巧之四
    深入理解object C中复制对象的用法(二)
    状压dp-poj-1170-Shopping Offers
    linux printk函数学习
    I.MX6 WIFI wireless_tools 移植
    I.MX6 AW-NB177NF WIFI 驱动移植问题
    VS 一些配置设置
    I.MX6 boot from Micro SD
    Android studio 构建太慢
    Android gif 录屏
  • 原文地址:https://www.cnblogs.com/justart/p/12023281.html
Copyright © 2011-2022 走看看