二、OpenResty实现缓存(nginx缓存)

本文介绍了如何使用OpenResty结合lua脚本来实现nginx缓存功能。通过修改nginx.conf配置,定义缓存空间,并在lua脚本中处理用户请求,实现从缓存、redis到mysql的数据读取逻辑。首次访问会将数据存入缓存,后续请求可直接从缓存获取,即使redis关闭,仍能正常访问。
摘要由CSDN通过智能技术生成

上一篇:OpenResty(lua脚本读mysql,写入redis):https://blog.csdn.net/qq_43220949/article/details/113784003)

这一篇是紧跟上一篇写的,上一篇实现了使用openresty的nginx转发请求到lua脚本执行,lua脚本查询mysql,存入redis。


使用openresty实现缓存(nginx缓存)

  1. 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脚本处理
  1. /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)
        
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值