OpenResty+nginx+lua+redis实现二级缓存
382 字
2 分钟
OpenResty+nginx+lua+redis实现二级缓存
-
下载OpenResty镜像
Terminal window docker pull openresty/openresty -
运行镜像
Terminal window docker run -d -p 880:80 --name openresty --restart always -v /etc/localtime:/etc/localtime openresty/openresty -
进入容器
Terminal window docker exec -it openresty /bin/bash -
安装lua
apt-get update -yapt-get install -y gccapt-get install -y curlapt-get install -y makeapt-get install -y vimapt-get install libreadline-dev -ycurl -R -O http://www.lua.org/ftp/lua-5.3.5.tar.gztar -zxf lua-5.3.5.tar.gzcd lua-5.3.5make linux testmake install -
编写lua脚本并上传到服务器
ngx.header.content_type = "application/json;charset=utf8"--获取本地缓存local cache_ngx = ngx.shared.dis_cache;-- 获取本地缓存数据local ngCache = cache_ngx:get('lua:application-data')if ngCache == "" or ngCache == nil then--引入redis库local cjson = require("cjson")local redis = require("resty.redis")local red = redis:new()red:set_timeout(2000)local ip = "127.0.0.1"local port = 6379red:connect(ip, port)red:auth("123456")local redCache = red:get("lua:application-data")if redCache == ngx.null or redCache == "" or redCache == nil then--引入mysql库local mysql = require("resty.mysql")local db = mysql:new()db:set_timeout(3000)local props = {host = "127.0.0.1",port = 3306,database = "test",user = "root",password = "root"}local res = db:connect(props)local select_sql = "SELECT xxx from tb_level where xxx"res = db:query(select_sql)db:close()red:set("lua:application-data", cjson.encode(res))red:close()--将redis中获取到的数据存入nginx本地缓存10分钟 测试阶段先1分钟cache_ngx:set('lua-game-milk-tea:level-data', cjson.encode(res), 1 * 60)ngx.say("{\"code\":0,\"message\":\"sql success\",\"data\":" .. cjson.encode(res) .. "}")else--将redis中获取到的数据存入nginx本地缓存10分钟 测试阶段先1分钟cache_ngx:set('lua:application-data', redCache, 1 * 60)ngx.say("{\"code\":0,\"message\":\"redis success\",\"data\":" .. redCache .. "}")endelsengx.say("{\"code\":0,\"message\":\"nginx success\",\"data\":" .. ngCache .. "}")end-
特别说明
lua读取redis数据返回结果为空时,返回的结果不是nil而是userdata类型的ngx.null
-
-
在http节点下开启nginx共享内存
Terminal window vim /usr/local/openresty/nginx/conf/nginx.conflua_shared_dict dis_cache 10m; -
在server节点添加lua配置
location /lua {content_by_lua_file /opt/lua/cache.lua;add_header Access-Control-Allow-Origin *;add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';add_header Access-Control-Allow-Headers '*';}
1624507084958 
1624507099317 
1624507152639
文章分享
如果这篇文章对你有帮助,欢迎分享给更多人!
OpenResty+nginx+lua+redis实现二级缓存
https://tianch.com.cn/posts/tutorials/openresty-nginx-lua-redis-shi-xian-er-ji-huan-cun/相关文章智能推荐
1
FRP v0.68.0 内网穿透完整教程
Nginx文档版本:v1.0 | 适用 FRP 版本:v0.68.0 | 更新日期:2026-07-31
2
Apollo生产环境分布式部署
中间件服务端基于Spring Boot,启动脚本理论上支持所有Linux发行版,建议CentOS 7。
3
JAVA设计模式的七大原则
其他2026-01-05
4
架构设计中的MySQL设计原则
MySQL单台服务器的存储能力及数据处理能力都是有限的, 因此需要增加服务器, 搭建集群来存储海量数据。
5
FlexVolume
KubernetesKubernetes 默认情况下就提供了主流的存储卷接入方案,可以执行命令 kubectl explain pod.spec.volumes 查看到支持的各种存储卷,另外也提供了插件机制,允许其他类型的存储服务接入到 Kubernetes
随机文章随机推荐


