多级缓存架构(三)OpenResty Lua缓存

news2024/9/28 17:25:20

文章目录

  • 一、nginx服务
  • 二、OpenResty服务
      • 1. 服务块定义
      • 2. 配置修改
      • 3. Lua程序编写
      • 4. 总结
  • 三、运行
  • 四、测试
  • 五、高可用集群
      • 1. openresty
      • 2. tomcat

通过本文章,可以完成多级缓存架构中的Lua缓存。
在这里插入图片描述
在这里插入图片描述

一、nginx服务

docker/docker-compose.yml中添加nginx服务块。

  nginx:
    container_name: nginx
    image: nginx:stable
    volumes:
      - ./nginx/conf/nginx.conf:/etc/nginx/nginx.conf
      - ./nginx/conf/conf.d/default.conf:/etc/nginx/conf.d/default.conf
      - ./nginx/dist:/usr/share/nginx/dist
    ports:
      - "8080:8080"
    networks:
      multi-cache:
        ipv4_address: 172.30.3.3

删除原来docker里的multiCache项目并停止springboot应用。

nginx部分配置如下,监听端口为8080,并且将请求反向代理至172.30.3.11,下一小节,将openresty固定在172.30.3.11

upstream nginx-cluster {
    server 172.30.3.11;
}

server {
    listen       8080;
    listen  [::]:8080;
    server_name  localhost;

    location /api {
        proxy_pass http://nginx-cluster;
    }
}

重新启动multiCache看看nginx前端网页效果。

docker-compose -p multi-cache up -d

访问http://localhost:8080/item.html?id=10001查询id=10001商品页
在这里插入图片描述
这里是假数据,前端页面会向/api/item/10001发送数据请求。

二、OpenResty服务

1. 服务块定义

docker/docker-compose.yml中添加openresty1服务块。

  openresty1:
    container_name: openresty1
    image: openresty/openresty:1.21.4.3-3-jammy-amd64
    volumes:
      - ./openresty1/conf/nginx.conf:/usr/local/openresty/nginx/conf/nginx.conf
      - ./openresty1/conf/conf.d/default.conf:/etc/nginx/conf.d/default.conf
      - ./openresty1/lua:/usr/local/openresty/nginx/lua
      - ./openresty1/lualib/common.lua:/usr/local/openresty/lualib/common.lua
    networks:
      multi-cache:
        ipv4_address: 172.30.3.11

2. 配置修改

前端向后端发送/api/item/10001请求关于id=10001商品信息。

根据nginx的配置内容,这个请求首先被nginx拦截,反向代理到172.30.3.11 (即openresty1)。

upstream nginx-cluster {
    server 172.30.3.11;
}

server {
    location /api {
        proxy_pass http://nginx-cluster;
    }
}

openresty1收到的也是/api/item/10001,同时,openresty/api/item/(\d+)请求代理到指定lua程序,在lua程序中完成数据缓存。
在这里插入图片描述
因此,openrestyconf/conf.d/default.conf如下

upstream tomcat-cluster {
    hash $request_uri;
    server 172.30.3.4:8081;
#     server 172.30.3.5:8081;
}

server {
    listen       80;
    listen  [::]:80;
    server_name  localhost;

    # intercept /item and join lua
    location ~ /api/item/(\d+) {
        default_type application/json;
        content_by_lua_file lua/item.lua;
    }

    # intercept lua and redirect to back-end
    location /path/ {
        rewrite ^/path/(.*)$ /$1 break;
        proxy_pass http://tomcat-cluster;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/dist;
    }
}

conf/nginx.confhttp块最后添加3行,引入依赖。

    #lua 模块
    lua_package_path "/usr/local/openresty/lualib/?.lua;;";
    #c模块
    lua_package_cpath "/usr/local/openresty/lualib/?.so;;";
    #本地缓存
    lua_shared_dict item_cache 150m;

3. Lua程序编写

common.lua被挂载到lualib,表示可以被其他lua当做库使用,内容如下

-- 创建一个本地缓存对象item_cache
local item_cache = ngx.shared.item_cache;

-- 函数,向openresty本身发送类似/path/item/10001请求,根据conf配置,将被删除/path前缀并代理至tomcat程序
local function read_get(path, params)
    local rsp = ngx.location.capture('/path'..path,{
        method = ngx.HTTP_GET,
        args = params,
    })
    if not rsp then
        ngx.log(ngx.ERR, "http not found, path: ", path, ", args: ", params);
        ngx.exit(404)
    end
    return rsp.body
end

-- 函数,如果本地有缓存,使用缓存,如果没有代理到tomcat然后将数据存入缓存
local function read_data(key, expire, path, params)
    -- query local cache
    local rsp = item_cache:get(key)
    -- query tomcat
    if not rsp then
        ngx.log(ngx.ERR, "redis cache miss, try tomcat, key: ", key)
        rsp = read_get(path, params)
    end
    -- write into local cache
    item_cache:set(key, rsp, expire)
    return rsp
end

local _M = {
    read_data = read_data
}

return _M

item.lua是处理来自形如/api/item/10001请求的程序,内容如下

-- include
local commonUtils = require('common')
local cjson = require("cjson")

-- get url params 10001
local id = ngx.var[1]
-- redirect item, 缓存过期时间1800s, 适合长时间不改变的数据
local itemJson = commonUtils.read_data("item:id:"..id, 1800,"/item/"..id,nil)
-- redirect item/stock, 缓存过期时间4s, 适合经常改变的数据
local stockJson = commonUtils.read_data("item:stock:id:"..id, 4 ,"/item/stock/"..id, nil)
-- json2table
local item = cjson.decode(itemJson)
local stock = cjson.decode(stockJson)
-- combine item and stock
item.stock = stock.stock
item.sold = stock.sold
-- return result
ngx.say(cjson.encode(item))

4. 总结

  1. 这里luaitem(tb_item表)和stock(tb_stock表)两个信息都有缓存,并使用cjson库将两者合并后返回到前端。
  2. 关于expire时效性的问题,如果后台改变了数据,但是openresty关于此数据的缓存未过期,前端得到的是旧数据
  3. 大致来说openresty = nginx + lua,不仅具有nginx反向代理的能力,还能介入lua程序进行扩展。

三、运行

到此为止,docker-compose.yml应该如下

version: '3.8'

networks:
  multi-cache:
    driver: bridge
    ipam:
      driver: default
      config:
        - subnet: 172.30.3.0/24

services:
  mysql:
    container_name: mysql
    image: mysql:8
    volumes:
      - ./mysql/conf/my.cnf:/etc/mysql/conf.d/my.cnf
      - ./mysql/data:/var/lib/mysql
      - ./mysql/logs:/logs
    ports:
      - "3306:3306"
    environment:
      - MYSQL_ROOT_PASSWORD=1009
    networks:
      multi-cache:
        ipv4_address: 172.30.3.2

  nginx:
    container_name: nginx
    image: nginx:stable
    volumes:
      - ./nginx/conf/nginx.conf:/etc/nginx/nginx.conf
      - ./nginx/conf/conf.d/default.conf:/etc/nginx/conf.d/default.conf
      - ./nginx/dist:/usr/share/nginx/dist
    ports:
      - "8080:8080"
    networks:
      multi-cache:
        ipv4_address: 172.30.3.3

  openresty1:
    container_name: openresty1
    image: openresty/openresty:1.21.4.3-3-jammy-amd64
    volumes:
      - ./openresty1/conf/nginx.conf:/usr/local/openresty/nginx/conf/nginx.conf
      - ./openresty1/conf/conf.d/default.conf:/etc/nginx/conf.d/default.conf
      - ./openresty1/lua:/usr/local/openresty/nginx/lua
      - ./openresty1/lualib/common.lua:/usr/local/openresty/lualib/common.lua
    networks:
      multi-cache:
        ipv4_address: 172.30.3.11

启动各项服务

docker-compose -p multi-cache up -d

启动springboot程序。
在这里插入图片描述

四、测试

清空openresty容器日志。
访问http://localhost:8080/item.html?id=10001
查看openresty容器日志,可以看到两次commonUtils.read_data都没有缓存,于是代理到tomcat,可以看到springboot日志出现查询相关记录。

2024-01-12 11:45:53 2024/01/12 03:45:53 [error] 7#7: *1 [lua] common.lua:99: read_data(): redis cache miss, try tomcat, key: item:id:10001, client: 172.30.3.3, server: localhost, request: "GET /api/item/10001 HTTP/1.0", host: "nginx-cluster", referrer: "http://localhost:8080/item.html?id=10001"
2024-01-12 11:45:53 2024/01/12 03:45:53 [error] 7#7: *1 [lua] common.lua:99: read_data(): redis cache miss, try tomcat, key: item:stock:id:10001 while sending to client, client: 172.30.3.3, server: localhost, request: "GET /api/item/10001 HTTP/1.0", host: "nginx-cluster", referrer: "http://localhost:8080/item.html?id=10001"
2024-01-12 11:45:53 172.30.3.3 - - [12/Jan/2024:03:45:53 +0000] "GET /api/item/10001 HTTP/1.0" 200 486 "http://localhost:8080/item.html?id=10001" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36 Edg/121.0.0.0"

再次访问此网址,强制刷新+禁用浏览器缓存+更换浏览器
间隔超过4s但小于1800s时,日志如下,只出现一次miss。

2024-01-12 11:48:04 2024/01/12 03:48:04 [error] 7#7: *4 [lua] common.lua:99: read_data(): redis cache miss, try tomcat, key: item:stock:id:10001, client: 172.30.3.3, server: localhost, request: "GET /api/item/10001 HTTP/1.0", host: "nginx-cluster", referrer: "http://localhost:8080/item.html?id=10001"
2024-01-12 11:48:04 172.30.3.3 - - [12/Jan/2024:03:48:04 +0000] "GET /api/item/10001 HTTP/1.0" 200 486 "http://localhost:8080/item.html?id=10001" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36 Edg/121.0.0.0"

再次访问此网址,强制刷新+禁用浏览器缓存+更换浏览器
间隔小于4s,日志如下,未出现miss。

2024-01-12 11:49:16 172.30.3.3 - - [12/Jan/2024:03:49:16 +0000] "GET /api/item/10001 HTTP/1.0" 200 486 "http://localhost:8080/item.html?id=10001" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36 Edg/121.0.0.0"

五、高可用集群

1. openresty

在这里插入图片描述
对于openresty高可用,可以部署多个openresty docker实例,并在nginxdocker/nginx/conf/conf.d/default.confupstream nginx-cluster将多个openresty地址添加进去即可。比如

upstream nginx-cluster {
	hash $request_uri;
	# hash $request_uri consistent;
    server 172.30.3.11;
    server 172.30.3.12;
    server 172.30.3.13;
}

多个openresty 无论是conf还是lua都保持一致即可。
并且使用hash $request_uri负载均衡作为反向代理策略,防止同一请求被多个实例缓存数据。

2. tomcat

在这里插入图片描述
对于springboot程序高可用,也是类似。可以部署多个springboot docker实例,并在openresty docker/openresty1/conf/conf.d/default.confupstream nginx-cluster将多个springboot地址添加进去即可。比如

upstream tomcat-cluster {
    hash $request_uri;
    server 172.30.3.4:8081;
    server 172.30.3.5:8081;
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1379425.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

canvasdrawer 微信原生小程序生成海报图片

在小程序中生成海报是一种非常有效的推广方式 用户可以使用小程序的过程中生成小程序海报并分享给他人 通过海报的形式,用户可以直观地了解产品或服务的特点和优势 常见绘制海报方式 目前,小程序海报有两种常见的实现方式: canvas 绘制…

Python基础语法汇总【保姆级小白教程】

文章目录 一:Python基础概念1.认识Python:2.Python的优势:3.Python的应用领域:4.Python的执行方式:5.文档: 二:变量与数据类型1.变量:2.id()函数:3.注释:4.基…

SqlAlchemy使用教程(一) 原理与环境搭建

一、SqlAlchemy 原理及环境搭建 SqlAlchemy是1个支持连接各种不同数据库的Python库,提供DBAPI与ORM(object relation mapper)两种方式使用数据库。 DBAPI方式,即使用SQL方式访问数据库 ORM, 对象关系模型,是用 Python…

竞赛保研 基于深度学习的视频多目标跟踪实现

文章目录 1 前言2 先上成果3 多目标跟踪的两种方法3.1 方法13.2 方法2 4 Tracking By Detecting的跟踪过程4.1 存在的问题4.2 基于轨迹预测的跟踪方式 5 训练代码6 最后 1 前言 🔥 优质竞赛项目系列,今天要分享的是 基于深度学习的视频多目标跟踪实现 …

Trans论文复现:基于数据驱动的新能源充电站两阶段规划方法程序代码!

适用平台:MatlabYalmipCplex/Gurobi; 文章提出了一种电动汽车充电站的两阶段规划方法,第一阶段通过蒙特卡洛法模拟充电车辆需求和电池充放电数据来确定充电站位置;第二阶段通过数据驱动的分布鲁棒优化方法优化充电站的新能源和电池…

Jenkins配置发邮件

Jenkins配置发邮件 账号设置 首先这个邮箱账号要支持发邮件,QQ邮箱开通SMTP即可之后要认证 企业微信邮箱 开启IMAP/SMTP服务开启POP/SMTP服务 无论是企业微信邮箱还是QQ邮箱都是SSL协议,在下面的配置中我都会勾选上!!&#xff0…

Nginx配置jks格式证书,升级https

通常在给服务器升级https,需要在nginx上配置域名对应的https证书,nginx通常配置的是crt和key格式的证书。最近遇到有人提供了jks格式的证书,查阅了几个资料都是需要先将jks转为p12格式,然后再将p12转为crt格式。这里记录一下相关过…

【自控实验】3. 带有饱和非线性环节控制系统相平面分析

本科课程实验报告,有太多公式和图片了,干脆直接转成图片了 仅分享和记录,不保证全对 实验内容: 有无非线性环节的相轨迹对比,并求超调量。 在输入单位阶跃信号Xsr时,用示波器观察和记录系统输入饱和非线…

复选框QCheckBox和分组框QGroupBox

1. 复选框:QCheckBox 实例化 //实例化 // QCheckBox* checkBox new QCheckBox("是否同意该条款",this);QCheckBox* checkBox new QCheckBox(this);1.1 代码实现 1.1.1 复选框的基本函数 复选框选中状态的参数 Qt::Unchecked //未选中状态 Qt::Part…

Java字符串拼接常用方法总结

使用场景:用某个分隔符拼接字符串 下边是我使用过的几种方式废话不多说,直接上代码初始数据 1.使用流2.StringBuilder3.[StringJoiner](https://blog.csdn.net/qq_43417581/article/details/126076152?ops_request_misc%257B%2522request%255Fid%2522%2…

win11下载Hbuliderx 安装闪退解决教程+安装包分享

在官网下载 目录 在官网下载 出现闪退 下载失败 2.2. 最终在百度网盘里下载了历史版本 2.3. 然后解压文件 2.4. 双击打开 2.5. 安装成功 出现闪退 下载失败 结果下载失败,一下子弹出的下载框就会闪退 2.2. 最终在百度网盘里下载了历史版本 下载的网盘链接: …

搭建个人智能家居 2 -安装ESPHome

搭建个人智能家居 2 -安装ESPHome 前言ESPHome Linux平台windows平台总结 前言 上一篇文章我们演示了多个平台下面搭建HomeAssistant,可能有一些小伙伴在安装、运行HomeAssistant OS后,打开HomeAssistant的控制台时会出现下面图片显示的问题 这一般是本…

Kibana:使用反向地理编码绘制自定义区域地图

Elastic 地图(Maps)附带预定义区域,可让你通过指标快速可视化区域。 地图还提供了绘制你自己的区域地图的功能。 你可以使用任何您想要的区域数据,只要你的源数据包含相应区域的标识符即可。 但是,当源数据不包含区域…

pytorch学习笔记(十)

一、损失函数 举个例子 比如说根据Loss提供的信息知道,解答题太弱了,需要多训练训练这个模块。 Loss作用:1.算实际输出和目标之间的差距 2.为我们更新输出提供一定的依据(反向传播) 看官方文档 每个输入输出相减取…

Springboot + vue 停车管理系统

Springboot vue 停车管理系统 项目描述 系统包含用户和管理员两个角色 用户:登录、注册、个人中心、预定停车位、缴费信息 管理员:登录、用户信息管理、车位信息管理、车位费用管理、停泊车辆管理、车辆进出管理、登录日志查询 运行环境 jdk1.8 idea …

畸变矫正-深度学习相关论文学习

目录 DocTr: Document Image Transformer for Geometric Unwarping and Illumination Correction SimFIR: A Simple Framework for Fisheye Image Rectification with Self-supervised Representation Learning Model-Free Distortion Rectification Framework Bridged by Di…

UCB Data100:数据科学的原理和技巧:第十一章到第十二章

十一、恒定模型、损失和转换 原文:Constant Model, Loss, and Transformations 译者:飞龙 协议:CC BY-NC-SA 4.0 学习成果 推导出在 MSE 和 MAE 成本函数下恒定模型的最佳模型参数。 评估 MSE 和 MAE 风险之间的差异。 理解变量线性化的必要…

Java中锁的解决方案

前言 在上一篇文章中,介绍了什么是锁,以及锁的使用场景,本文继续给大家继续做深入的介绍,介绍JAVA为我们提供的不同种类的锁。 JAVA为我们提供了种类丰富的锁,每种锁都有不同的特性,锁的使用场景也各不相…

【C】volatile 关键字

目录 volatile1)基本概念2)用途:禁止编译器优化3)总结 volatile 1)基本概念 const是C语言的一个关键字。 const用于告诉编译器相应的变量可能会在程序的控制之外被修改,因此编译器不应该对其进行优化。 …

mac 使用brew卸载node

1.查看当前的node版本 node -v 2.查看使用brew 安装的版本,可以看到本机装了14、16、18版本的node brew search node 3.卸载node brew uninstall node版本号 --force 如分别删除14、16、18版本的node命令如下 brew uninstall node14 --force brew uninstall no…