上一篇:OpenResty(lua脚本读mysql,写入redis):https://blog.csdn.net/qq_43220949/article/details/113784003)
这一篇是紧跟上一篇写的,上一篇实现了使用openresty的nginx转发请求到lua脚本执行,lua脚本查询mysql,存入redis。
使用openresty实现缓存(nginx缓存)
- nginx.conf修改
# 定义nginx缓存模块 dis_cache
lua_shared_dict dis_cache 5m;
server {
listen 80;
server_name localhost;
location /update {
content_by_lua_file /root/lua/68/ad_update.lua;
}
# 用户请求read?id=1,将该请求转到/root/lua/68/ad_update.lua脚本处理
location /read {
content_by_lua_file /root/lua/68/ad_read.lua;
}
....
}
- 定义nginx缓存空间
- 用户请求read?id=1,将该请求转到ad_update.lua脚本处理
- /root/lua/68/ad_read.lua
ngx.header.content_type="application/json;charset=utf8"
--获取请求中的参数ID
local uri_args = ngx.req.get_uri_args();
local position = uri_args["id"];
--获取nginx本地缓存dis_cache
local cache_ngx = ngx.shared.dis_cache;
--根据ID 获取nginx本地缓存数据
local adCache = cache_ngx:get('ad_cache_'..position);
if adCache == "" or adCache == nil then
--引入redis库
local redis = require("resty.redis");
--创建redis对象
local red = redis:new()
--设置超时时间
red:set_timeout(2000)
--连接
local ok, err = red:connect("127.0.0.1", 6379)