OpenResty 连接Redis
1 创建redis配置模块
cd /usr/local/openresty/nginx/lua/conf
vim redis_conf.lualocal redis_c = require "resty.redis"local ok, new_tab = pcall(require, "table.new")
if not ok or type(new_tab) ~= "function" thennew_tab = function (narr, nrec) return {} end
endlocal _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" thenfor k,v in pairs(res) doif v ~= ngx.null thenreturn falseendendreturn trueelseif res == ngx.null thenreturn trueelseif res == nil thenreturn trueendreturn false
end-- change connect address as you need
function _M.connect_mod( self, redis )redis:set_timeout(self.timeout)return redis:connect("192.168.38.80", 6379)
endfunction _M.set_keepalive_mod( redis )-- put it into the connection pool of size 100, with 60 seconds max idle timereturn redis:set_keepalive(60000, 1000)
endfunction _M.init_pipeline( self )self._reqs = {}
endfunction _M.commit_pipeline( self )local reqs = self._reqsif nil == reqs or 0 == #reqs thenreturn {}, "no pipeline"elseself._reqs = nilendlocal redis, err = redis_c:new()if not redis thenreturn nil, errendlocal ok, err = self:connect_mod(redis)if not ok thenreturn {}, errendredis:init_pipeline()for _, vals in ipairs(reqs) dolocal fun = redis[vals[1]]table.remove(vals , 1)fun(redis, unpack(vals))endlocal results, err = redis:commit_pipeline()if not results or err thenreturn {}, errendif is_redis_null(results) thenresults = {}ngx.log(ngx.WARN, "is null")end-- table.remove (results , 1)self.set_keepalive_mod(redis)for i,value in ipairs(results) doif is_redis_null(value) thenresults[i] = nilendendreturn results, err
endfunction _M.subscribe( self, channel )local redis, err = redis_c:new()if not redis thenreturn nil, errendlocal ok, err = self:connect_mod(redis)if not ok or err thenreturn nil, errendlocal res, err = redis:subscribe(channel)if not res thenreturn nil, errendres, err = redis:read_reply()if not res thenreturn nil, errendredis:unsubscribe(channel)self.set_keepalive_mod(redis)return res, err
endlocal function do_command(self, cmd, ... )if self._reqs thentable.insert(self._reqs, {cmd, ...})returnendlocal redis, err = redis_c:new()if not redis thenreturn nil, errendlocal ok, err = self:connect_mod(redis)if not ok or err thenreturn nil, errendlocal 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, errendif is_redis_null(result) thenresult = nilendself.set_keepalive_mod(redis)return result, err
endfor i = 1, #commands dolocal cmd = commands[i]_M[cmd] =function (self, ...)return do_command(self, cmd, ...)end
endfunction _M.new(self, opts)opts = opts or {}local timeout = (opts.timeout and opts.timeout * 1000) or 1000local db_index= opts.db_index or 0return setmetatable({timeout = timeout,db_index = db_index,_reqs = nil }, mt)
endreturn _M
2 修改nginx.conf
http {include mime.types;default_type application/octet-stream;sendfile on;keepalive_timeout 65;lua_package_path "/usr/local/openresty/nginx/lua/conf/?.lua;;";server {listen 80;server_name localhost;lua_code_cache on;location / {root html;index index.html index.htm;}location /test_redis {default_type 'text/html';content_by_lua_file lua/test_redis.lua;}}}
3 创建test_redis.lua
local redis = require "redis_conf"
local red = redis:new()local ok, err = red:set("dog", "an animal")
if not ok thenngx.say("failed to set dog: ", err)return
endlocal res, err = red:get("dog")
if not res thenngx.say("failed to get dog: ", err)return
endngx.say("res: ", res)
4 重启
/usr/local/openresty/nginx/sbin/nginx -c /usr/local/openresty/nginx/conf/nginx.conf -s reload
5 测试
http://192.168.38.80/test_redis
OpenResty 连接Redis相关推荐
- Openresty最佳案例 | 第7篇: 模块开发、OpenResty连接Redis
Lua模块开发 在实际的开发过程中,不可能把所有的lua代码写在一个lua文件中,通常的做法将特定功能的放在一个lua文件中,即用lua模块开发.在lualib目录下,默认有以下的lua模块. lua ...
- CentOS6.4 安装OpenResty和Redis 并在Nginx中利用lua简单读取Redis数据
1.下载OpenResty和Redis OpenResty下载地址:wget http://openresty.org/download/ngx_openresty-1.4.3.6.tar.gz Re ...
- lua 连接redis集群
1.连接redis集群需要用到llua-resty-redis-cluster模块 github地址:https://github.com/cuiweixie/lua-resty-redis-clus ...
- openresty 操作 redis
文章目录 1.redis连接池 2.编写测试脚本 前言: openresty .lua .redis 的 安装这里就不再赘述了,请自行百度. 使用到了OpenResty,很核心的目的是为了解决高并发的 ...
- RedisClient 连接redis 提示 ERR Client sent AUTH, but no password is set
使用redisclient连接redis出现上图的错误 在配置中已经找到requirepass修改了密码,但是还是出现上图错误.在网上找了资料在dos设置 出现上图红框中的错误,研究了半天也没有解决. ...
- [ 搭建Redis本地服务器实践系列三 ] :图解Redis客户端工具连接Redis服务器
原文:[ 搭建Redis本地服务器实践系列三 ] :图解Redis客户端工具连接Redis服务器 上一章 [ 搭建Redis本地服务器实践系列二 ] :图解CentOS7配置Redis 介绍了Red ...
- Redis系列-远程连接redis并给redis加锁
假设两台Redis服务器,ip分别为:192.168.1.101和192.168.1.103,如何在101上通过redis-cli访问103上的redis呢?在远程连接103之前,先讲下redis-c ...
- 使用RedisDesktopManager客户端无法连接Redis服务器问题解决办法
使用RedisDesktopManager客户端无法连接Redis服务器问题解决办法 参考文章: (1)使用RedisDesktopManager客户端无法连接Redis服务器问题解决办法 (2)ht ...
- linux下搭建redis并解决无法连接redis的问题
linux下搭建redis并解决无法连接redis的问题 参考文章: (1)linux下搭建redis并解决无法连接redis的问题 (2)https://www.cnblogs.com/bestmy ...
最新文章
- 【TensorFlow】:Eager Mode(动态图模式)
- louvian算法 缺点 优化_机器学习中的优化算法(1)-优化算法重要性,SGD,Momentum(附Python示例)...
- xp系统如何开启索引服务器,Windows XP系统关闭磁盘索引的两个方法图文教程
- c++ 获取线程id_5分钟带你完全理解什么是线程
- 玩转jquery插件之flexigrid 【转】
- struts2源码系列(3)--拦截器
- MATLAB数据拟合时出错
- Java计算机毕业设计大学生企业推荐系统源码+系统+数据库+lw文档
- MinGW-w64的安装及配置教程
- es 排序 聚合统计_ES聚合排序java
- 服务器多开安卓系统,安卓云服务器能多开吗
- 薄膜单点压力传感器的制作
- 网格布局---grid
- linux ppp拨号 USB,Linux中实现ppp拨号连接
- [禅悟人生]有自知之明, 在深浅之间权衡做人
- Tp5自动加载创建admin和index文件夹
- 寒假训练第九场 Brocard Point of a Triangle
- 小米前端实习电话面试一面
- ElementUI Tree 树形结构展示
- 为空口“定制”L2:MAC、RLC、PDCP和SDAP子层之MAC