openresty开发系列27--openresty中封装redis操作

在关于web+lua+openresty开发中,项目中会大量操作redis,

重复创建连接-->数据操作-->关闭连接(或放到连接池)这个完整的链路调用完毕,
甚至还要考虑不同的 return 情况做不同处理,就很快发现代码中有大量的重复

推荐一个二次封装的类库
---------------------------------
# 加入openresty的lib库目录
# vim openresty/lualib/resty/redis_iresty.lua

local redis_c = require "resty.redis"

local ok, new_tab = pcall(require, "table.new")
if not ok or type(new_tab) ~= "function" then
    new_tab = function (narr, nrec) return {} end
end

local _M = new_tab(0, 155)
_M._VERSION = '0.01'

local commands = {
    "append",            "auth",              "bgrewriteaof",
    "bgsave",            "bitcount",          "bitop",
    "blpop",             "brpop",
    "brpoplpush",        "client",            "config",
    "dbsize",
    "debug",             "decr",              "decrby",
    "del",               "discard",           "dump",
    "echo",
    "eval",              "exec",              "exists",
    "expire",            "expireat",          "flushall",
    "flushdb",           "get",               "getbit",
    "getrange",          "getset",            "hdel",
    "hexists",           "hget",              "hgetall",
    "hincrby",           "hincrbyfloat",      "hkeys",
    "hlen",
    "hmget",              "hmset",      "hscan",
    "hset",
    "hsetnx",            "hvals",             "incr",
    "incrby",            "incrbyfloat",       "info",
    "keys",
    "lastsave",          "lindex",            "linsert",
    "llen",              "lpop",              "lpush",
    "lpushx",            "lrange",            "lrem",
    "lset",              "ltrim",             "mget",
    "migrate",
    "monitor",           "move",              "mset",
    "msetnx",            "multi",             "object",
    "persist",           "pexpire",           "pexpireat",
    "ping",              "psetex",            "psubscribe",
    "pttl",
    "publish",      --[[ "punsubscribe", ]]   "pubsub",
    "quit",
    "randomkey",         "rename",            "renamenx",
    "restore",
    "rpop",              "rpoplpush",         "rpush",
    "rpushx",            "sadd",              "save",
    "scan",              "scard",             "script",
    "sdiff",             "sdiffstore",
    "select",            "set",               "setbit",
    "setex",             "setnx",             "setrange",
    "shutdown",          "sinter",            "sinterstore",
    "sismember",         "slaveof",           "slowlog",
    "smembers",          "smove",             "sort",
    "spop",              "srandmember",       "srem",
    "sscan",
    "strlen",       --[[ "subscribe",  ]]     "sunion",
    "sunionstore",       "sync",              "time",
    "ttl",
    "type",         --[[ "unsubscribe", ]]    "unwatch",
    "watch",             "zadd",              "zcard",
    "zcount",            "zincrby",           "zinterstore",
    "zrange",            "zrangebyscore",     "zrank",
    "zrem",              "zremrangebyrank",   "zremrangebyscore",
    "zrevrange",         "zrevrangebyscore",  "zrevrank",
    "zscan",
    "zscore",            "zunionstore",       "evalsha"
}

local mt = { __index = _M }

local function is_redis_null( res )
    if type(res) == "table" then
        for k,v in pairs(res) do
            if v ~= ngx.null then
                return false
            end
        end
        return true
    elseif res == ngx.null then
        return true
    elseif res == nil then
        return true
    end

return false
end

function _M.close_redis(self, redis)  
    if not redis then  
        return  
    end  
    --释放连接(连接池实现)
    local pool_max_idle_time = self.pool_max_idle_time --最大空闲时间 毫秒  
    local pool_size = self.pool_size --连接池大小  
    
    local ok, err = redis:set_keepalive(pool_max_idle_time, pool_size)  
    if not ok then  
        ngx.say("set keepalive error : ", err)  
    end  
end

-- change connect address as you need
function _M.connect_mod( self, redis )
    redis:set_timeout(self.timeout)
        
    local ok, err = redis:connect(self.ip, self.port)
    if not ok then  
        ngx.say("connect to redis error : ", err)  
        return self:close_redis(redis)  
    end
    
    if self.password then ----密码认证
        local count, err = redis:get_reused_times()
        if 0 == count then ----新建连接,需要认证密码
            ok, err = redis: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

return ok,err;
end

function _M.init_pipeline( self )
    self._reqs = {}
end

function _M.commit_pipeline( self )
    local reqs = self._reqs

if nil == reqs or 0 == #reqs then
        return {}, "no pipeline"
    else
        self._reqs = nil
    end

local redis, err = redis_c:new()
    if not redis then
        return nil, err
    end

local ok, err = self:connect_mod(redis)
    if not ok then
        return {}, err
    end

redis:init_pipeline()
    for _, vals in ipairs(reqs) do
        local fun = redis[vals[1]]
        table.remove(vals , 1)

fun(redis, unpack(vals))
    end

local results, err = redis:commit_pipeline()
    if not results or err then
        return {}, err
    end

if is_redis_null(results) then
        results = {}
        ngx.log(ngx.WARN, "is null")
    end
    -- table.remove (results , 1)

--self.set_keepalive_mod(redis)
    self:close_redis(redis)

for i,value in ipairs(results) do
        if is_redis_null(value) then
            results[i] = nil
        end
    end

return results, err
end

local function do_command(self, cmd, ... )
    if self._reqs then
        table.insert(self._reqs, {cmd, ...})
        return
    end

local redis, err = redis_c:new()
    if not redis then
        return nil, err
    end

local ok, err = self:connect_mod(redis)
    if not ok or err then
        return nil, err
    end

redis:select(self.db_index)
    
    local fun = redis[cmd]
    local result, err = fun(redis, ...)
    if not result or err then
        -- ngx.log(ngx.ERR, "pipeline result:", result, " err:", err)
        return nil, err
    end

if is_redis_null(result) then
        result = nil
    end

--self.set_keepalive_mod(redis)
    self:close_redis(redis)

return result, err
end

for i = 1, #commands do
    local cmd = commands[i]
    _M[cmd] =
            function (self, ...)
                return do_command(self, cmd, ...)
            end
end

function _M.new(self, opts)
    opts = opts or {}
    local timeout = (opts.timeout and opts.timeout * 1000) or 1000
    local db_index= opts.db_index or 0
    local ip = opts.ip or '127.0.0.1'
    local port = opts.port or 6379
    local password = opts.password
    local pool_max_idle_time = opts.pool_max_idle_time or 60000
    local pool_size = opts.pool_size or 100

return setmetatable({
            timeout = timeout,
            db_index = db_index,
            ip = ip,
            port = port,
            password = password,
            pool_max_idle_time = pool_max_idle_time,
            pool_size = pool_size,
            _reqs = nil }, mt)
end

return _M

---------------------------------------
调用案例

local redis = require "resty.redis_iresty"

local opts = {
    ip = "10.11.0.215",
    port = "6379",
    password = "redis123",
    db_index = 1
}

local red = redis:new(opts)

local ok, err = red:set("dog", "an animal")
if not ok then
    ngx.say("failed to set dog: ", err)
    return
end

ngx.say("set result: ", ok)

---------------------------------------
管道

redis.set
redis.get

red:init_pipeline()
red:set("cat", "Marry")
red:set("horse", "Bob")
red:get("cat")
red:get("horse")
local results, err = red:commit_pipeline()
if not results then
    ngx.say("failed to commit the pipelined requests: ", err)
    return
end

for i, res in ipairs(results) do
    ngx.say(res,"<br/>");
end

在日常的开发中我们不需要重复造轮子,只要这个轮子 稳定,高效就可以直接拿过来用

转载于:https://www.cnblogs.com/reblue520/p/11434632.html

openresty开发系列27--openresty中封装redis操作相关推荐

  1. openresty开发系列26--openresty中使用redis模块

    openresty开发系列26--openresty中使用redis模块 在一些高并发的场景中,我们常常会用到缓存技术,现在我们常用的分布式缓存redis是最知名的, 操作redis,我们需要引入re ...

  2. openresty开发系列38--通过Lua+Redis 实现动态封禁IP

    openresty开发系列38--通过Lua+Redis 实现动态封禁IP 一)需求背景为了封禁某些爬虫或者恶意用户对服务器的请求,我们需要建立一个动态的 IP 黑名单.对于黑名单之内的 IP ,拒绝 ...

  3. openresty开发系列28--openresty中操作mysql

    openresty开发系列28--openresty中操作mysql Mysql客户端    应用中最常使用的就是数据库了,尤其mysql数据库,那openresty lua如何操作mysql呢?   ...

  4. openresty开发系列25--openresty中使用json模块

    openresty开发系列25--openresty中使用json模块 web开发过程中,经常用的数据结构为json,openresty中封装了json模块,我们看如何使用 一)如何引入cjson模块 ...

  5. openresty开发系列29--openresty中发起http请求

    openresty开发系列29--openresty中发起http请求 有些场景是需要nginx在进行请求转发 用户浏览器请求url访问到nginx服务器,但此请求业务需要再次请求其他业务: 如用户请 ...

  6. openresty开发系列24--openresty中lua的引入及使用

    openresty开发系列24--openresty中lua的引入及使用 openresty 引入 lua 一)openresty中nginx引入lua方式 1)xxx_by_lua   ---> ...

  7. openresty开发系列16--lua中的控制结构if-else/repeat/for/while

    openresty开发系列16--lua中的控制结构if-else/repeat/for/while一)条件 - 控制结构 if-else if-else 是我们熟知的一种控制结构.Lua 跟其他语言 ...

  8. openresty开发系列37--nginx-lua-redis实现访问频率控制

    openresty开发系列37--nginx-lua-redis实现访问频率控制 一)需求背景 在高并发场景下为了防止某个访问ip访问的频率过高,有时候会需要控制用户的访问频次 在openresty中 ...

  9. openresty开发系列23--lua面向对象

    openresty开发系列23--lua面向对象 面向对象编程(Object Oriented Programming,OOP)是一种非常流行的计算机编程架构. java,c++,.net等都支持面向 ...

最新文章

  1. Couldn't start MySQL! while starting XAMPP
  2. 51Nod-1082 与7无关的数【进制+打表】
  3. React Native 红屏之Could not connect to development server.
  4. c语言中猴子拿香蕉的代码题,猴子分香蕉(2018年第九届蓝桥杯省赛第二题)
  5. 再见,Eclipse...
  6. 服务上的图片直接在浏览器上可以打开,但是在img上报404错误
  7. 微信小程序中app.js文件、组件、api
  8. 《Spring2之站立会议5》
  9. SEC0000007-Unable to locate security server?
  10. php数据库模式,具有singleton模式的PHP数据库类[closed]
  11. 纯HTML的个人简历,真的超简单,有源码
  12. Unity编辑器控制粒子系统Playback Time
  13. 好玩的猜数游戏(不是二分查找!四位数)
  14. 《关于我横扫一线厂的那些面经》拼多多Java岗(附答案)
  15. Python爬虫三:抓取链家已成交二手房信息(58W数据)
  16. 2009年必看十大动漫游戏改编电影
  17. 儒猿秒杀季!ZooKeeper从0基础到源码级大神课
  18. ##微信小程序页面跳转##
  19. IOT设备配网绑定通讯流程
  20. 联想创投大数据基于开源技术 助力全球智能制造

热门文章

  1. c语言的简单题目,C语言的一些简单题目,没有答案,哪位大神帮忙做一下!!!...
  2. No module named MNIST_写给小白的用fashion-mnist入门机器学习和深度学习的简单项目(非常全面!!!)...
  3. (JAVA学习笔记) 如何计算2*8效率高(面试题)—— 左移和右移问题。
  4. 【排序算法】图解桶排序
  5. Android SnackBar:你值得拥有的信息提示控件
  6. Servlet优化之BaseServlet
  7. Oracle with子句的简单介绍.
  8. php access ole相片,[求助]怎样读取ACCESS数据库中的OLE对象的图片啊???
  9. 手机上可以学python吗_Python爬虫也能用手机进行抓包?没错!这个技巧我只告诉你...
  10. P1014Cantor表(找规律)