lua加openRestry实现缓存预热与二级缓存

缓存预热(将mysql数据查询出来存放到redis)

实现思路:
在这里插入图片描述

步骤一:编写lua脚本实现缓存预热(将mysql里的数据查询出来存入redis)

定义请求:用于查询数据库中的数据更新到redis中

先链接mysql,按照广告分类ID读取广告列表,转换为json字符

链接redis,将广告列表json字符串存入redis

定义请求:

请求:
/ad_update
参数:
position ‐‐指定广告位置
返回值:
json

--代表当前要进行json数据的传递
ngx.header.content_type="application/json;charset=utf8"
--通过require引入了两个模块(cjson,mysql)
local cjson = require("cjson")
local mysql = require("resty.mysql")
--当前要获取到的请求路径的参数,返回给uri_args局部变量
local uri_args = ngx.req.get_uri_args()
--拿到请求路径后,通过请求路径获取它特定的值,position
local position = uri_args["position"]
--开启mysql的一个新的链接
local db = mysql:new()
--设置数据库链接超时的时间
db:set_timeout(1000)  
--链接mysql的信息
local props = {  
    --ip
    host = "127.0.0.1",  
    --端口
    port = 3306,  
    --数据库名
    database = "cg_business",  
    --账号
    user = "root",  
    --密码
    password = "root"  
}  
--基于这些参数来进行mysql链接
local res = db:connect(props)  
--链接mysql之后要执行的sql语句,..是字符串的拼接
local select_sql = "select url,image from tb_ad where status ='1' and position='"..position.."' and start_time<= NOW() AND end_time>= NOW()" 
--db:query里面来传递要执行的sql
res = db:query(select_sql)  
--关闭数据库的链接
db:close()  
--通过require来引入redis的模块
local redis = require("resty.redis")
--开启redis的新的链接
local red = redis:new()
--设置redis的链接超时时间
red:set_timeout(2000)
--redis的ip
local ip ="127.0.0.1"
--redis的端口号
local port = 6379
--connect 开启redis的链接
red:connect(ip,port)
red:auth(password)  --redis密码
red:select(1)   --选择16个数据库中的一个
--red:se 当前要向redis中存放哪些内容,..是字符串的拼接
red:set("ad_"..position,cjson.encode(res))
--关闭redis
red:close()
--整个lua脚本执行完成后返回一句话
ngx.say("{\"flag\":true,\"position\":\""..position.."\"}")

修改/usr/local/openresty/nginx/conf/nginx.conf文件:

代码如下:

 server {
        listen       80;
        server_name  localhost;
        charset utf-8;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;
        #添加广告,基于content_by_lua_file属性来加载特定的某lua文件
        location  /ad_update{
           content_by_lua_file  /root/lua/ad_update.lua;
        }
        # 读取广告
        location /ad_read {
            content_by_lua_file /root/lua/ad_read.lua;
        }

重新启动nginx
测试:http://127.0.0.1/ad_update?position=web_index_lb

缓存预热与二级缓存查询

步骤二:编写lua脚本实现二级缓存读取

在这里插入图片描述

广告缓存读取(将redis中的数据响应给前端)
定义请求:

请求:/ad_read
参数:position
返回值:json

在/root/lua目录下创建ad_read.lua

--设置响应头类型
ngx.header.content_type="application/json;charset=utf8"
--获取请求中的参数ID
local uri_args = ngx.req.get_uri_args();
local position = uri_args["position"];

--获取本地缓存
local cache_ngx = ngx.shared.dis_cache;
--根据ID 获取本地缓存数据
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)
ok,err = red:auth(password)  --redis密码
ok,err = red:select(1)   --选择16个数据库中的一个
--获取key的值
local rescontent=red:get("ad_"..position)
--输出到返回响应中
ngx.say(rescontent)
--关闭连接
red:close()
--将redis中获取到的数据存入nginx本地缓存
cache_ngx:set('ad_cache_'..position, rescontent, 10*60);

else
 --nginx本地缓存中获取到数据直接输出
 ngx.say(adCache)
end

在 /usr/local/openresty/nginx/conf/nginx.conf中server下添加配置

server {
    listen       80;
    server_name  localhost;
    charset utf-8;

    #charset koi8-r;

    #access_log  logs/host.access.log  main;
    #添加广告
    location  /ad_update{
       content_by_lua_file  /root/lua/ad_update.lua;
    }
    # 读取广告
    location /ad_read {
        content_by_lua_file /root/lua/ad_read.lua;
    }

    location / {
        root   html;
        index  index.html index.htm;
    }

修改nginx配置文件vi /usr/local/openresty/nginx/conf/nginx.conf ,http节点下添加配置:

#包含redis初始化模块
lua_shared_dict dis_cache 5m;  #共享内存开启

测试 http://127.0.0.1/ad_read?position=web_index_lb
https://blog.csdn.net/ww55123793/article/details/108590564

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
是的,OpenResty可以通过Lua脚本和Redis数据库来动态获取upstream。具体实现方式如下: 1. 在Nginx配置文件中定义upstream,并将upstream的backend地址设置为一个占位符,例如: ``` upstream backend { server 127.0.0.1:8080; } server { location / { proxy_pass http://backend; } } ``` 2. 在Lua脚本中连接Redis数据库,并获取upstream的backend地址列表。例如: ``` local redis = require "resty.redis" local red = redis:new() -- 连接Redis数据库 red:set_timeout(1000) local ok, err = red:connect("127.0.0.1", 6379) if not ok then ngx.log(ngx.ERR, "failed to connect to Redis: ", err) return ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR) end -- 获取backend地址列表 local backend_list, err = red:smembers("backend_list") if not backend_list then ngx.log(ngx.ERR, "failed to get backend list from Redis: ", err) return ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR) end -- 关闭Redis连接 red:set_keepalive(10000, 100) -- 将backend地址列表设置到upstream中 local upstream = require "ngx.upstream" local backend_servers = {} for i, backend in ipairs(backend_list) do table.insert(backend_servers, {["server"] = backend}) end local ok, err = upstream.set_servers("backend", backend_servers) if not ok then ngx.log(ngx.ERR, "failed to update backend servers: ", err) return ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR) end ``` 3. 在Nginx配置文件中引入Lua脚本,并定时执行该脚本。例如: ``` lua_shared_dict backend 1m; upstream backend { server 127.0.0.1:8080; } server { location / { access_by_lua_file "/path/to/lua/script.lua"; proxy_pass http://backend; } } ``` 这样,当Redis数据库中的backend地址列表发生变化时,Lua脚本会自动更新upstream的backend地址,并实现动态负载均衡。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

-梦与时光遇-

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值