nginx(OpenResty)+lua+redis实现缓存预热或二级缓存查询

nginx(OpenResty)+lua+redis实现缓存预热或二级缓存查询

在电商项目中可以用来处理广告的缓存

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

    图解:在这里插入图片描述

  • 编写lua脚本实现二级缓存读取

    图解:在这里插入图片描述

一丶实现缓存预热

实现思路:

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

(1)连接mysql ,按照广告分类ID读取广告列表,转换为json字符串。

(2)连接redis,将广告列表json字符串存入redis 。

定义请求:

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

在/root/lua目录下创建ad_load.lua ,实现连接mysql 查询数据 并存储到redis中。

ngx.header.content_type="application/json;charset=utf8"
local cjson = require("cjson")
local mysql = require("resty.mysql")
local uri_args = ngx.req.get_uri_args()
local position = uri_args["position"]

local db = mysql:new()
db:set_timeout(1000)  
local props = {  
    host = "192.168.200.128",  
    port = 3306,  
    database = "changgou_business",  
    user = "root",  
    password = "root"  
}

local res = db:connect(props)  
local select_sql = "select url,image from tb_ad where status ='1' and position='"..position.."' and start_time<= NOW() "  
res = db:query(select_sql)  
db:close()  

local redis = require("resty.redis")
local red = redis:new()
red:set_timeout(2000)

local ip ="192.168.200.128"
local port = 6379
red:connect(ip,port)

red:set("ad_"..position,cjson.encode(res))
red:close()

ngx.say("{flag:true}")

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

代码如下:

#user  nobody;
user root root;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    server {
        listen       80;
        server_name  localhost;
        charset utf-8;
        #access_log  logs/host.access.log  main;
        # 添加
        location /ad_update {
            content_by_lua_file /root/lua/ad_update.lua;
        }
        
        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }        
    }
}

重新启动nginx 在nginx的sbin目录下

./nginx -s reload

测试:http://192.168.200.128/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"

local uri_args = ngx.req.get_uri_args();
local position = uri_args["position"];

local redis = require("resty.redis");

local red = redis:new()

red:set_timeout(2000)

local ok, err = red:connect("192.168.200.128", 6379)

local rescontent=red:get("ad_"..position)

ngx.say(rescontent)

red:close()

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

location /ad_read {
  content_by_lua_file /root/lua/ad_read.lua;
}

测试 http://192.168.200.128/ad_read?position=web_index_lb 输出

[{"url":"img\/banner1.jpg","image":"img\/banner1.jpg"},{"url":"img\/banner2.jpg","image":"img\/banner2.jpg"}]

三丶 二级缓存-加入openresty本地缓存

如上的方式没有问题,但是如果请求都到redis,redis压力也很大,所以我们一般采用多级缓存的方式来减少下游系统的服务压力。

先查询openresty本地缓存 如果没有再查询redis中的数据

  • 修改/root/lua目录下ad_read文件, 内容如下:
ngx.header.content_type="application/json;charset=utf8"
local uri_args = ngx.req.get_uri_args();
local position = uri_args["position"];
local cache_ngx = ngx.shared.dis_cache;
local adCache = cache_ngx:get('ad_cache_'..position);
if adCache == "" or adCache == nil then
    local redis = require("resty.redis");
    local red = redis:new()
    red:set_timeout(2000)
    local ok, err = red:connect("192.168.200.128", 6379)
    local rescontent=red:get("ad_"..position)
    ngx.say(rescontent)
    red:close()
    cache_ngx:set('ad_cache_'..position, rescontent, 10*60);
else
    ngx.say(adCache)
end
  • 修改nginx配置文件vi /usr/local/openresty/nginx/conf/nginx.conf ,http节点下添加配置:
#包含redis初始化模块
lua_shared_dict dis_cache 5m;  #共享内存开启
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值