lua模块demo(redis,http,mysql,cjson,本地缓存)
1. lua模块demo(redis,http,mysql,cjson,本地缓存)
1.1. 配置
- 在nginx.conf中设置lua_shared_dict my_cache 128m; 开启nginx本地缓存,放到http{} 层
- location配置
location /redis-get{
resolver 8.8.8.8;
default_type text/html;
content_by_lua_file /usr/local/openresty/lua/redis-get.lua;
}
- 这里推荐个工具,使用notepad++,下载个插件NppFtp,效果如下图,可以直接对liunx上的文件进行编辑保存

1.2. http
- 远程调用可以使用该模块 https://github.com/ledgetech/lua-resty-http
- 把lib包里的两个文件复制到 /usr/local/openresty/lualib/resty
- 通过require("resty.http") 调用
1.3. mysql
- 连接工具
local connectMysqlUtil = {}
local mysql = require "resty.mysql"
-- connect to mysql;
function connectMysqlUtil.connect()
local db, err = mysql:new()
if not db then
return false
end
db:set_timeout(1000)
local ok, err, errno, sqlstate = db:connect{
host = "127.0.0.1",
port = 8083,
database = "test",
user = "dev",
password = "1234",
max_packet_size = 1024 * 1024 }
if not ok then
ngx.say("connect mysql failed")
return false
end
return db
end
return connectMysqlUtil
1.4. string工具
local stringEx = {}
function stringEx.ToStringEx(value)
if type(value)=='table' then
return stringEx.TableToStr(value)
elseif type(value)=='string' then
return "\'"..value.."\'"
else
return tostring(value)
end
end
function stringEx.TableToStr(t)
if t == nil then return "" end
local retstr= "{"
local i = 1
for key,value in pairs(t) do
local signal = ","
if i==1 then
signal = ""
end
if key == i then
retstr = retstr..signal..stringEx.ToStringEx(value)
else
if type(key)=='number' or type(key) == 'string' then
retstr = retstr..signal..'['..stringEx.ToStringEx(key).."]="..stringEx.ToStringEx(value)
else
if type(key)=='userdata' then
retstr = retstr..signal.."*s"..stringEx.TableToStr(getmetatable(key)).."*e".."="..stringEx.ToStringEx(value)
else
retstr = retstr..signal..key.."="..stringEx.ToStringEx(value)
end
end
end
i = i+1
end
retstr = retstr.."}"
return retstr
end
function stringEx.StrToTable(str)
if str == nil or type(str) ~= "string" then
return
end
return loadstring("return " .. str)()
end
return stringEx
1.5. 整合redis+本地缓存
-- 自定义的字符串转换工具
local stringEx = require("stringExt")
-- 本地缓存
local local_cache = ngx.shared.my_cache
-- redis连接池,设置连接空闲时间
local function close_redis(red)
if not red then
return
end
local pool_max_idle_time = 10000
local pool_size = 100
local ok,err = red:set_keepalive(pool_max_idle_time,pool_size)
if not ok then
ngx.say("set keepalive fail ",err)
end
end
-- 读redis缓存
local function read_redis(key)
local redis = require("resty.redis")
local red = redis.new();
local ok,err = red:connect("127.0.0.1",8084)
if not ok then
ngx.say("connect fail ",err)
return close_redis(red)
end
red:set_timeout(1000)
local count,err = red:get_reused_times()
if 0==count then
ok,err = red:auth("123456")
if not ok then
ngx.say("auth fail ",err)
return close_redis(red)
end
elseif err then
ngx.say("fail to get reused times")
return close_redis(red)
end
local res,err = red:get(key)
if not res then
ngx.say("get msg fail ",err)
return close_redis(red)
elseif res then
ngx.say(" set expire 10000 ")
red:expire(key,10)
end
local_cache:set(key,res,5)
ngx.say("read from redis ")
ngx.say(res)
close_redis(red)
end
-- http请求参数
local args = ngx.req.get_uri_args()
local key = args["key"]
if not key then
ngx.say("key must be exist")
return
end
local keyCache = local_cache:get(key)
if not keyCache then
local res = read_redis(key)
if not res then
ngx.say("redis is null")
end
else
ngx.say("read from localCache ")
ngx.say(keyCache)
end
-- http调用工具,需要额外下载,地址:https://github.com/ledgetech/lua-resty-http 说明:https://blog.csdn.net/xiejunna/article/details/53445342
local http = require("resty.http")
local httpc = http.new();
if not httpc then
ngx.say("\n\r httpc new fail")
end
httpc:set_timeout(8000)
-- keepalive参数不写可能导致报错
local res,err = httpc:request_uri("http://www.xxx.com",{
method="POST",
path="/xxx/rpc.api",
body = 'a=1&b=2',
headers = {
["Content-Type"] = "application/x-www-form-urlencoded",
},
keepalive_timeout = 60,
keepalive_pool = 10
})
if not res then
ngx.say("httpc call fail ")
return
end
local cjson = require("cjson")
local json = cjson.new()
if not json then
ngx.say("json is null")
return
end
-- 测试调用结果
-- ngx.say(stringEx.TableToStr(res))
-- ngx.say(stringEx.ToStringEx(json.decode(res["body"])))
-- ngx.say(type(json.decode(res["body"])))
-- ngx.say(stringEx.ToStringEx(json.decode(res["body"])["header"]["request_seq"]))
-- ngx.say(type(json.decode(res["body"])["header"]))
-- ngx.say(type(json.decode(res["body"])["header"]["request_seq"]))
local connectMysqlUtil = require("connectMysqlUtil")
local db = connectMysqlUtil.connect()
if not db then
ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
return
end
local res,err,errcode,sqlstate = db:query("select * from t_uls_order_info where order_id='20190119232946000023'",10)
if not res then
ngx.say("bad request: ",err,":",errcode,": ",sqlstate,".")
return
end
ngx.say("result:",json.encode(res))
1.6. 总结
- 本文记录了对http,mysql,redis,nginx本地缓存的基本使用方式,后续需要使用到该模块的需求可以直接参考修改本示例代码
- 对于实际的互联网需求,这里可以想象个基于这些模块的需求,优先读取ngnix本地缓存,过期时间较短,其次读取redis缓存,减少redis压力,进一步减少mysql读取压力
lua模块demo(redis,http,mysql,cjson,本地缓存)的更多相关文章
- Nginx Lua拓展模块操作Redis、Mysql
# Nginx的拓展模块 # ngx_lua模块 # 淘宝开发的ngx_lua模块通过lua解释器集成近Nginx,可以采用lua脚本实现业务逻辑,由于lua的紧凑.快速以及内建协程,所以在保证宝兵法 ...
- redis实现mysql的数据缓存
环境设定base2 172.25.78.12 nginx+phpbase3 172.25.78.13 redis端base4 172.25.78.14 mysql端# 1.在base2(nginx+p ...
- 用Redis作为Mysql数据库的缓存【转】
用Redis作Mysql数据库缓存,必须解决2个问题.首先,应该确定用何种数据结构存储来自Mysql的数据:在确定数据结构之后,还要考虑用什么标识作为该数据结构的键. 直观上看,Mysql中的数据都是 ...
- redis订阅发布消息操作本地缓存
Redis 本地缓存+远程缓存方案 使用纯java的ehcache作为本地缓存 Reids 作为远程分布式缓存 解决redis缓存压力过大,提高缓存速度,以及缓存性能. Redis和ehcache缓存 ...
- redis(三)--用Redis作为Mysql数据库的缓存
把MySQL结果集缓存到Redis的字符串或哈希结构中以后,我们面临一个新的问题,即如何为这些字符串或哈希命名,也就是如何确定它们的键.因为这些数据结构所对应的行都属于某个结果集,假如可以找到一种唯一 ...
- 用Redis作为Mysql数据库的缓存
看到一篇不错的博文,记录下: http://blog.csdn.net/qtyl1988/article/details/39553339 http://blog.csdn.net/qtyl1988/ ...
- 利用Azure Redis Cache构建百万量级缓存读写
Redis是一个非常流行的基于内存的,低延迟,高吞吐量的key/value数据存储,被广泛用于数据库缓存,session的管理,热数据高速访问,甚至作为数据库方式提高应用程序可扩展性,吞吐量,和实施处 ...
- 本地缓存下载文件,download的二次封装
来源:http://ask.dcloud.net.cn/article/524 源码下载链接 说明: (1)由于平时项目中大量用到了附件下载等功能,所以就花了一个时间,把plus的downlaod进行 ...
- lua入门demo(HelloWorld+redis读取)
1. lua入门demo 1.1. 入门之Hello World!! 由于我习惯用docker安装各种软件,这次的lua脚本也是运行在docker容器上 openresty是nginx+lua的各种模 ...
随机推荐
- centos7 删除swap
https://www.refmanual.com/2016/01/08/completely-remove-swap-on-ce7/#.W8AaSRMzaRs 删除不干净,启动不起来的情况下.需要从 ...
- hbase-运维命令
hbase 问题 不一致问题 meta表不一致问题 hdfs文件不一致问题 hbase hbck hbase hbck 用于检测和修改hbase底层文件问题.检测像master,region serv ...
- sqoop mysql导入hive 数值类型变成null的问题分析
问题描述:mysql通过sqoop导入到hive表中,发现有个别数据类型为int或tinyint的列导入后数据为null.设置各种行分隔符,列分隔符都没有效果. 问题分析:hive中单独将有问题的那几 ...
- 《探索未知种族之osg类生物》目录
精力有限,博客园不在更新<探索未知种族之osg类生物>.在这里列出所有文章目录(持续更新)有兴趣的同学可以看看. 探索未知种族之osg类生物[目录] 前序 探索未知种族之osg类生物--- ...
- oracle redo日志文件损坏恢复
参考:How to Recover from Loss Of Online Redo Log And ORA-312 And ORA-313 (Doc ID 117481.1) 在线重做日志文件丢失后 ...
- ssh多台主机之间不用密码远程
二.多台服务器相互无密码访问 多台服务器相互无密码访问,与两台服务器单向无密码访问的原理是一样的,只不过由于是多台服务器之间相互无密码访问,不能象两台服务器无密码登录那样直接上传,步骤如下: 1.在需 ...
- spring+struts+hibernate整合
spring整合: 1:添加配置文件和相应的spring jar包(记得一定要加上commons-logging的jar包,有坑****) 2:创建date对象,如果成功则spring的环境ok
- 【NIFI】 Apache NiFI 使用技巧
本章介绍NIFI组件的使用. 主要有:Nginx反向代理NIFI,配置SSLContextService Nginx反向代理NIFI 使用nginx反向代理NIFI配置如下 upstream nifi ...
- springmvc 简单使用
一.配置(使用)流程 1.新建maven工程,在pom.xml中导入相关包,重要的是springmvc包,servlet包,jstl包 <dependencies> ...
- https多网站1个IP多个SSL证书的Apache设置办法
这些天接触了解SSL证书后,写了一篇<申请免费的SSL证书,开通https网站>博文,其中简单记录了Apache的设置,后来又涉及到多个域名.泛域名解析.通配符SSL证书.单服务器/多服务 ...