微服务21_多级缓存02:OpenResty/Redis/Nginx

  • 一、安装OpenResty
  • 1、安装开发库、仓库、安装OpenResty
  • 2、配置环境变量
  • 3.启动和运行
  • 4.备注
  • 二、OpenResty快速入门
  • 1、反向代理流程
  • 2、OpenResty监听请求
  • 3、编写item.lua
  • 三、请求参数处理
  • 1.获取参数的API
  • 2.获取参数并返回。Openresy获取请求id,拼接到返回结果中
  • 四、openResty直接查询Tomcat
  • 1.发送http请求的API。原理:
  • 2.封装http工具 实践:
  • 3.CJSON工具类的使用:
  • 4.实现Tomcat查询
  • 5.基于ID负载均衡
  • 1)原理
  • 2)实现
  • 3)测试
  • 五、Redis缓存预热
  • 六、OpenResty中实现查询Redis
  • 1.封装Redis工具。学习:
  • 完整的common.lua:
  • 2.实现Redis查询。
  • 3.测试:
  • 七、Nginx本地缓存【在OpenResty添加本地缓存】
  • 1.本地缓存API
  • 4.7.2.实现本地缓存查询
  • 测试:


多级缓存:

有个静态页面item.html放在了windows上面的Nginx,充当静态资源服务器和反向代理服务器。当用户请求的时候将页面返回用户的浏览器,当浏览器渲染页面的时候,发现缺少数据,就会发送Ajax请求来查询数据,那么windows的Nginx不会处理,而是反向代理给Linux中的Nginx集群。该集群也是一个本地缓存数据。所以说是返回数据的第一站。负载均衡根据id固定请求一个服务器。
如果Nginx本地缓存未命中,则去查询Redis缓存。Redis是缓存第二站
如果Redis缓存未命中,再根据id负载均衡的请求,JVM的Tomcat进程缓存。JVM进程缓存第三站
如果三级缓存都未命中,再去mysql数据中查询数据

缓存同步:

设置有效期:Nginx
异步同步:redis和进程缓存

微服务间数据缓存 微服务多级缓存_nginx

一、安装OpenResty

OpenResty是一个基于Nginx的高性能Web平台,用户方便的搭建能够处理高并发、扩展性极高的动态Web应用、Web服务和动态网关。具备以下特点:

  • 具备Nginx的完整功能
  • 基于Lua语言进行扩展,集成了大量精良的Lua库、第三方模块
  • 允许使用Lua自定义业务逻辑、自定义库

官网:https://openresty.org/cn/

1、安装开发库、仓库、安装OpenResty

  1. 安装开发库
    首先要安装OpenResty的依赖开发库,执行命令:
yum install -y pcre-devel openssl-devel gcc --skip-broken
  1. 安装OpenResty仓库

你可以在你的 CentOS 系统中添加 openresty 仓库,这样就可以便于未来安装或更新我们的软件包(通过 yum check-update 命令)。运行下面的命令就可以添加我们的仓库:

yum-config-manager --add-repo https://openresty.org/package/centos/openresty.repo

如果提示说命令不存在,则运行:

yum install -y yum-utils

然后再重复上面的命令

  1. 安装OpenResty

然后就可以像下面这样安装软件包,比如 openresty

yum install -y openresty
  1. 安装opm工具

opm是OpenResty的一个管理工具,可以帮助我们安装一个第三方的Lua模块。

如果你想安装命令行工具 opm,那么可以像下面这样安装 openresty-opm 包:

yum install -y openresty-opm
  1. 目录结构

默认情况下,OpenResty安装的目录是:/usr/local/openresty

  • 看到里面的nginx目录了,和Windows的Nginx目录几乎一样。OpenResty就是在Nginx基础上集成了一些Lua模块。
  • openRest的bin目录就是可执行文件目录。其中有一个openresty文件是一个软连接,连接到了Nginx的Bin中的可执行文件。 当启动openresty时,实际是启动的Nginx。 当然也可以直接启动Nginx
  • 微服务间数据缓存 微服务多级缓存_Nginx_02

  • luajit和lualib其实是openresty提供的第三方模块。比如说操作redis或者mysql这些工具模块都已经封装到了模块中了。 所以只要是集成了目录中的插件,就能实现功能了。

微服务间数据缓存 微服务多级缓存_springboot_03

2、配置环境变量

  1. 配置nginx的环境变量
    把Nginx目录放到环境变量的path中,这样到任何目录下,都可以运行Nginx。
    打开配置文件:
vi /etc/profile

在最下面加入两行:

export NGINX_HOME=/usr/local/openresty/nginx
export PATH=${NGINX_HOME}/sbin:$PATH

NGINX_HOME:后面是OpenResty安装目录下的nginx的目录

然后让配置生效:

source /etc/profile

微服务间数据缓存 微服务多级缓存_微服务间数据缓存_04

3.启动和运行

OpenResty底层是基于Nginx的,查看OpenResty目录的nginx目录,结构与windows中安装的nginx基本一致:

所以运行方式与nginx基本一致:

# 启动nginx
nginx
# 重新加载配置
nginx -s reload
# 停止
nginx -s stop

nginx的默认配置文件注释太多,影响后续我们的编辑,这里将nginx.conf中的注释部分删除,保留有效部分。

修改/usr/local/openresty/nginx/conf/nginx.conf文件,内容如下:

#user  nobody;
worker_processes  1;
error_log  logs/error.log;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;

    server {
        listen       8081;
        server_name  localhost;
        location / {
            root   html;
            index  index.html index.htm;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

在Linux的控制台输入命令以启动nginx:

nginx

微服务间数据缓存 微服务多级缓存_springboot_05

然后访问页面:http://IP地址和端口号,注意ip地址替换为你自己的虚拟机IP:

微服务间数据缓存 微服务多级缓存_Nginx_06

4.备注

加载OpenResty的lua模块:

#lua 模块
lua_package_path "/usr/local/openresty/lualib/?.lua;;";
#c模块     
lua_package_cpath "/usr/local/openresty/lualib/?.so;;";

common.lua

-- 封装函数,发送http请求,并解析响应
local function read_http(path, params)
    local resp = ngx.location.capture(path,{
        method = ngx.HTTP_GET,
        args = params,
    })
    if not resp then
        -- 记录错误信息,返回404
        ngx.log(ngx.ERR, "http not found, path: ", path , ", args: ", args)
        ngx.exit(404)
    end
    return resp.body
end
-- 将方法导出
local _M = {  
    read_http = read_http
}  
return _M

释放Redis连接API:

-- 关闭redis连接的工具方法,其实是放入连接池
local function close_redis(red)
    local pool_max_idle_time = 10000 -- 连接的空闲时间,单位是毫秒
    local pool_size = 100 --连接池大小
    local ok, err = red:set_keepalive(pool_max_idle_time, pool_size)
    if not ok then
        ngx.log(ngx.ERR, "放入redis连接池失败: ", err)
    end
end

读取Redis数据的API:

-- 查询redis的方法 ip和port是redis地址,key是查询的key
local function read_redis(ip, port, key)
    -- 获取一个连接
    local ok, err = red:connect(ip, port)
    if not ok then
        ngx.log(ngx.ERR, "连接redis失败 : ", err)
        return nil
    end
    -- 查询redis
    local resp, err = red:get(key)
    -- 查询失败处理
    if not resp then
        ngx.log(ngx.ERR, "查询Redis失败: ", err, ", key = " , key)
    end
    --得到的数据为空处理
    if resp == ngx.null then
        resp = nil
        ngx.log(ngx.ERR, "查询Redis数据为空, key = ", key)
    end
    close_redis(red)
    return resp
end

开启共享词典:

# 共享字典,也就是本地缓存,名称叫做:item_cache,大小150m
lua_shared_dict item_cache 150m;

二、OpenResty快速入门

1.Windows中的Nginx返回请求静态页面,将路径转到Linux中的8081端口

微服务间数据缓存 微服务多级缓存_springboot_07

2.在Linux的openresty中监听8081端口,在编写location 监听路径。【相当于controller】
3.交给lua文件去处理【相当于service】
4.ngx.say(‘’) 返回的是:json格式的假数据。

1、反向代理流程

现在,商品详情页使用的是假的商品数据。不过在浏览器中,可以看到页面有发起ajax请求查询真实商品数据。

请求地址是localhost,端口是80,就被windows上安装的Nginx服务给接收到了。然后代理给了OpenResty集群:

微服务间数据缓存 微服务多级缓存_lua_08

2、OpenResty监听请求

1、如何在Linux中的OpenRest接受请求?
接受请求是:
location后面跟着请求路径。下面写业务逻辑

OpenResty的很多功能都依赖于其目录下的Lua库,需要在nginx.conf中指定依赖库的目录,并导入依赖:

1)添加对OpenResty的Lua模块的加载

修改/usr/local/openresty/nginx/conf/nginx.conf文件,在其中的http下面,添加下面代码:
加载工具模块,访问redis等需要这些工具模块

#lua 模块
lua_package_path "/usr/local/openresty/lualib/?.lua;;";
#c模块     
lua_package_cpath "/usr/local/openresty/lualib/?.so;;";

微服务间数据缓存 微服务多级缓存_springboot_09

2)监听/api/item路径

修改/usr/local/openresty/nginx/conf/nginx.conf文件,在nginx.conf的server下面,添加对/api/item这个路径的监听:

location  /api/item {
    # 默认的响应类型
    default_type application/json;
    # 响应结果由lua/item.lua文件来决定
    # 我的内容是由lua文件来决定的
    content_by_lua_file lua/item.lua;
}

这个监听,就类似于SpringMVC中的@GetMapping("/api/item")做路径映射。

content_by_lua_file lua/item.lua则相当于调用item.lua这个文件,执行其中的业务,把结果返回给用户。相当于java中调用service。

微服务间数据缓存 微服务多级缓存_lua_10

创建这个相当于service的文件:

微服务间数据缓存 微服务多级缓存_Nginx_11

3、编写item.lua

1)在/usr/loca/openresty/nginx目录创建文件夹:lua
2)在/usr/loca/openresty/nginx/lua文件夹下,新建文件:item.lua

微服务间数据缓存 微服务多级缓存_springboot_12

3)编写item.lua,返回假数据

在这个文件中是可以编写返回数据的。这次虽然返回的是假数据,但是可以调用查redis、Tomcat、mysql的数据等等。

item.lua中,利用ngx.say()函数返回数据到Response中

ngx.say('{"id":10001,"name":"SALSA AIR","title":"RIMOWA 21寸托运箱拉杆箱 SALSA AIR系列果绿色 820.70.36.4","price":17900,"image":"https://m.360buyimg.com/mobilecms/s720x720_jfs/t6934/364/1195375010/84676/e9f2c55f/597ece38N0ddcbc77.jpg!q70.jpg.webp","category":"拉杆箱","brand":"RIMOWA","spec":"","status":1,"createTime":"2019-04-30T16:00:00.000+00:00","updateTime":"2019-04-30T16:00:00.000+00:00","stock":2999,"sold":31290}')

4)重新加载配置

nginx -s reload

刷新商品页面:http://localhost/item.html?id=1001,即可看到效果:

微服务间数据缓存 微服务多级缓存_微服务间数据缓存_13

三、请求参数处理

上述是返回的固定假数据,那么在实际业务中是根据请求不同,返回不同的数据。得到不同请求的参数。如何在openresy中获取用户的请求参数呢?

1.获取参数的API

OpenResty中提供了一些API用来获取不同类型的前端请求参数:

  • 路径占位符:匹配到的正则表达式的值放到了:ngx.var的数组中。
    取数组中的元素,是用角标从1来取。从而获取路径中的参数。
  • 请求头:调用API即可。返回的是一个table。因为请求头是多个,K,v结构
    req就是request的缩写代表请求。
    get_header() 获取请求头
  • 微服务间数据缓存 微服务多级缓存_微服务间数据缓存_14

2.获取参数并返回。Openresy获取请求id,拼接到返回结果中

在前端发起的ajax请求如图:

微服务间数据缓存 微服务多级缓存_微服务间数据缓存_15

可以看到商品id是以路径占位符方式传递的,因此可以利用正则表达式匹配的方式来获取ID。

1)获取商品id

修改/usr/loca/openresty/nginx/nginx.conf文件中监听/api/item的代码,利用正则表达式获取ID:
\d+表示能获取到所有数字类型的

location ~ /api/item/(\d+) {
    # 默认的响应类型
    default_type application/json;
    # 响应结果由lua/item.lua文件来决定
    content_by_lua_file lua/item.lua;
}

2)拼接ID并返回

修改/usr/loca/openresty/nginx/lua/item.lua文件,获取id并拼接到结果中返回:

-- 获取商品id
local id = ngx.var[1]
-- 拼接并返回
ngx.say('{"id":' .. id .. ',"name":"SALSA AIR","title":"RIMOWA 21寸托运箱拉杆箱 SALSA AIR系列果绿色 820.70.36.4","price":17900,"image":"https://m.360buyimg.com/mobilecms/s720x720_jfs/t6934/364/1195375010/84676/e9f2c55f/597ece38N0ddcbc77.jpg!q70.jpg.webp","category":"拉杆箱","brand":"RIMOWA","spec":"","status":1,"createTime":"2019-04-30T16:00:00.000+00:00","updateTime":"2019-04-30T16:00:00.000+00:00","stock":2999,"sold":31290}')

3)重新加载并测试
运行命令以重新加载OpenResty配置:

nginx -s reload

刷新页面可以看到结果中已经带上了ID:动态ID

微服务间数据缓存 微服务多级缓存_lua_16


微服务间数据缓存 微服务多级缓存_nginx_17

四、openResty直接查询Tomcat

第三节:能拿到前端传过来的请求参数。那么就应该对请求参数进行相应查询数据。例如根据获取到不同的请求id,返回数据。
目前已经准备好了,Nginx反向代理的服务器,接受前端的请求,并且转到OPenResty。那么openResty该去哪里查数据呢? 应该是:先查本地openResty缓存,然后未命中再去查redis、jvmTomcat缓存、数据库等。
那么就应该先把Tomcat缓存,存到openResty本地缓存当中。
在服务端也准备好了,编写了JVM进程缓存。

拿到商品ID后,本应去缓存中查询商品信息,不过目前我们还未建立nginx、redis缓存。因此,这里我们先根据商品id去tomcat查询商品信息。我们实现如图部分:

微服务间数据缓存 微服务多级缓存_微服务间数据缓存_18


需要注意的是,我们的OpenResty是在虚拟机,Tomcat是在Windows电脑上。两者IP一定不要搞错了。ifconfig / ipconfig

微服务间数据缓存 微服务多级缓存_lua_19


微服务间数据缓存 微服务多级缓存_springboot_20

1.发送http请求的API。原理:

nginx提供了内部API用以发送http请求:
capture:捕获的意思,捕获一个请求。
参数1:请求的路径。
参数2:是一个table

local resp = ngx.location.capture("/path",{
    method = ngx.HTTP_GET,   -- 请求方式
    args = {a=1,b=2},  -- get方式传参数
})

返回值是:resp【response对象】
返回的响应内容包括:

  • resp.status:响应状态码
  • resp.header:响应头,是一个table
  • resp.body:响应体,就是响应数据。是一个JSON的字符串

发请求的地址应该是:ip和端口+请求路径
注意:这里的path是路径,并不包含IP和端口。这个请求会被nginx内部的server监听并处理。

但是我们希望这个请求发送到Tomcat服务器,所以还需要编写一个server来对这个路径做反向代理:

location /path {
     # 这里是windows电脑的ip和Java服务端口,需要确保windows防火墙处于关闭状态
     # 这里是反向代理
     proxy_pass http://192.168.150.1:8081; 
 }

原理如图:

微服务间数据缓存 微服务多级缓存_springboot_21

2.封装http工具 实践:

下面,我们封装一个发送Http请求的工具,基于ngx.location.capture来实现查询tomcat。

1)添加反向代理,到windows的Java服务

因为item-service中的接口都是/item开头,所以我们监听/item路径,代理到windows上的tomcat服务。

修改 /usr/local/openresty/nginx/conf/nginx.conf文件,添加一个location:

location /item {
    proxy_pass http://192.168.150.1:8081;
}

微服务间数据缓存 微服务多级缓存_Nginx_22

以后,只要我们调用ngx.location.capture("/item"),就一定能发送请求到windows的tomcat服务。

2)封装工具类

之前我们说过,OpenResty启动时会加载以下两个目录中的工具文件:

配置加载lua模块的配置:

这个后缀名为.lua 的文件都会被加载

微服务间数据缓存 微服务多级缓存_lua_23


所以,自定义的http工具也需要放到这个目录下。那么以后在/usr/local/openresty/nginx/conf/nginx.conf引入后,直接用就行了,就可以接受到所有的HTTP请求了。

/usr/local/openresty/lualib目录下,新建一个common.lua文件:

vi /usr/local/openresty/lualib/common.lua

内容如下:
发送请求(方法参数:请求路径、请求方式、请求的参数)

-- 封装函数,发送http请求,并解析响应
local function read_http(path, params)
    local resp = ngx.location.capture(path,{
        method = ngx.HTTP_GET,
        args = params,
    })
    -- 查询失败:
    --   取反:如果未查到 not nil-> true :打印日志ngx.log(查询错误)
    if not resp then
        -- 记录错误信息,返回404
        ngx.log(ngx.ERR, "http请求查询失败, path: ", path , ", args: ", args)
        ngx.exit(404)
    end
    -- 查询成功:返回json字符串
    return resp.body
end
-- 将方法导出
-- 以后凡是调用common.lua文件,返回的是_M 的read_http的函数
local _M = {  
    read_http = read_http
}  
return _M

这个工具将read_http函数封装到_M这个table类型的变量中,并且返回,这类似于导出。

使用的时候,可以利用require('common')来导入该函数库,这里的common是函数库的文件名。

3)实现商品查询

最后,我们修改/usr/local/openresty/lua/item.lua文件,利用刚刚封装的函数库实现对tomcat的查询:

-- 引入自定义common工具模块,返回值是common中返回的 _M
local common = require("common")
-- 从 common中获取read_http这个函数
local read_http = common.read_http
-- 获取路径参数
local id = ngx.var[1]
-- 根据id查询商品
local itemJSON = read_http("/item/".. id, nil)
-- 根据id查询商品库存
local itemStockJSON = read_http("/item/stock/".. id, nil)

-- 拼接并返回 这里可以测试一下,只返回item 商品信息:
ngx.say(itemJSON)

微服务间数据缓存 微服务多级缓存_lua_24


微服务间数据缓存 微服务多级缓存_nginx_25

这里查询到的结果是json字符串,并且包含商品、库存两个json字符串,页面最终需要的是把两个json拼接为一个json:

这就需要我们先把JSON变为lua的table,完成数据整合后,再转为JSON。

微服务间数据缓存 微服务多级缓存_springboot_26

3.CJSON工具类的使用:

OpenResty提供了一个cjson的模块用来处理JSON的序列化和反序列化。

官方地址: https://github.com/openresty/lua-cjson/

1)引入cjson模块:

local cjson = require "cjson"

2)序列化:

local obj = {
    name = 'jack',
    age = 21
}
-- 把 table 序列化为 json
local json = cjson.encode(obj)

3)反序列化:

local json = '{"name": "jack", "age": 21}'
-- 反序列化 json为 table
local obj = cjson.decode(json);
print(obj.name)

4.实现Tomcat查询

下面,我们修改之前的item.lua中的业务,添加json处理功能:

-- 导入common函数库
local common = require('common')
local read_http = common.read_http

-- 导入 cjson库
local cjson = require('cjson')

-- 获取路径参数
local id = ngx.var[1]											 

-- 查询商品信息
local itemJSON = read_http("/item/" .. id, nil)
-- 查询库存信息
local stockJSON = read_http("/item/stock/" .. id,nil)

-- 将json 数据转为lua的table,反序列化
local item = cjson.decode(itemJSON)
local stock = cjson.decode(stockJSON)

-- 将库存信息,赋值到商品信息中:
item.stock = stock.stock
item.sold = stock.sold

-- 把item序列化为json 返回结果
ngx.say(cjson.encode(item))

我这里报错500. 即使我复制的代码,也是500 。无奈…
通过查看日志:lua entry thread aborted: runtime error: /usr/local/openresty/nginx/lua/item.lua:13: attempt to call global ‘red_http’ (a nil value)
得知代码敲错了

微服务间数据缓存 微服务多级缓存_微服务间数据缓存_27

微服务间数据缓存 微服务多级缓存_lua_28

微服务间数据缓存 微服务多级缓存_lua_29

5.基于ID负载均衡

刚才的代码中,我们的tomcat是单机部署。而实际开发中,tomcat一定是集群模式:

微服务间数据缓存 微服务多级缓存_nginx_30

因此,OpenResty需要对tomcat集群做负载均衡。

而默认的负载均衡规则是轮询模式,当我们查询/item/10001时:

  • 第一次会访问8081端口的tomcat服务,在该服务内部就形成了JVM进程缓存
  • 第二次会访问8082端口的tomcat服务,该服务内部没有JVM缓存(因为JVM缓存无法共享),会查询数据库

你看,因为轮询的原因,第一次查询8081形成的JVM缓存并未生效,直到下一次再次访问到8081时才可以生效,缓存命中率太低了。

怎么办?

如果能让同一个商品,每次查询时都访问同一个tomcat服务,那么JVM缓存就一定能生效了。

也就是说,我们需要根据商品id做负载均衡,而不是轮询。

1)原理

nginx提供了基于请求路径做负载均衡的算法:

nginx根据请求路径做hash运算,把得到的数值对tomcat服务的数量取余,余数是几,就访问第几个服务,实现负载均衡。

例如:

  • 我们的请求路径是 /item/10001
  • tomcat总数为2台(8081、8082)
  • 对请求路径/item/1001做hash运算求余的结果为1
  • 则访问第一个tomcat服务,也就是8081

只要id不变,每次hash运算结果也不会变,那就可以保证同一个商品,一直访问同一个tomcat服务,确保JVM缓存生效。

2)实现

修改/usr/local/openresty/nginx/conf/nginx.conf文件,实现基于ID做负载均衡。

微服务间数据缓存 微服务多级缓存_nginx_31

首先,定义tomcat集群,并设置基于路径做负载均衡:

upstream tomcat-cluster {
    hash $request_uri;
    server 192.168.150.1:8081;
    server 192.168.150.1:8082;
}

然后,修改对tomcat服务的反向代理,目标指向tomcat集群:

location /item {
    proxy_pass http://tomcat-cluster;
}

重新加载OpenResty

nginx -s reload
3)测试

启动两台tomcat服务:

微服务间数据缓存 微服务多级缓存_lua_32


清空日志后,再次访问页面,可以看到不同id的商品,访问到了不同的tomcat服务:

微服务间数据缓存 微服务多级缓存_微服务间数据缓存_33


不管刷新多少次,都不会在重新去数据库查询数据了!!!

只要id不变,每次hash运算结果也不会变,那就可以保证同一个商品,一直访问同一个tomcat服务,确保JVM缓存生效。

五、Redis缓存预热

在第四节中,当请求经过OpenResty后不能直接到达JVM进程缓存,而是先到达Redis,在redis未命中时,在进行缓存查询

微服务间数据缓存 微服务多级缓存_springboot_34

edis缓存会面临冷启动问题:

冷启动:服务刚刚启动时,Redis中并没有缓存,如果所有商品数据都在第一次查询时添加缓存,可能会给数据库带来较大压力。

缓存预热:在实际开发中,我们可以利用大数据统计用户访问的热点数据,在项目启动时将这些热点数据提前查询并保存到Redis中。

我们数据量较少,并且没有数据统计相关功能,目前可以在启动时将所有数据都放入缓存中。

1)利用Docker安装Redis

docker run --name redis -p 6379:6379 -d redis redis-server --appendonly yes

docker 状态为Exited

微服务间数据缓存 微服务多级缓存_nginx_35

2)在item-service服务中引入Redis依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

3)配置Redis地址

spring:
  redis:
    host: 192.168.150.101

4)编写初始化类

缓存预热需要在项目启动时完成,并且必须是拿到RedisTemplate之后。

这里我们利用InitializingBean接口来实现,因为InitializingBean可以在对象被Spring创建并且成员变量全部注入后执行。

需要在项目启动时操作缓存:
注册一个Bean ,并且实现BeanInitializingBean就必须实现afterpropertiesSet方法,该方法会在该方法创建之后进行创建。
项目启动的时候创建Bean,然后注入对象,然后调用afterPropertiesSet方法 进程初始化缓存

package com.heima.item.config;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.heima.item.pojo.Item;
import com.heima.item.pojo.ItemStock;
import com.heima.item.service.IItemService;
import com.heima.item.service.IItemStockService;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class RedisHandler implements InitializingBean {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private IItemService itemService;
    @Autowired
    private IItemStockService stockService;
	
	// spring默认的JSON工具
	//JSON序列化:writevalueasString(将实体类转为JSON)
    private static final ObjectMapper MAPPER = new ObjectMapper();

    @Override
    public void afterPropertiesSet() throws Exception {
        // 初始化缓存
        // 1.查询商品信息
        List<Item> itemList = itemService.list();
        // 2.放入缓存
        for (Item item : itemList) {
            // 2.1.item序列化为JSON
            String json = MAPPER.writeValueAsString(item);
            // 2.2.存入redis
            redisTemplate.opsForValue().set("item:id:" + item.getId(), json);
        }

        // 3.查询商品库存信息
        List<ItemStock> stockList = stockService.list();
        // 4.放入缓存
        for (ItemStock stock : stockList) {
            // 2.1.item序列化为JSON
            String json = MAPPER.writeValueAsString(stock);
            // 2.2.存入redis
            redisTemplate.opsForValue().set("item:stock:id:" + stock.getId(), json);
        }
    }
}

微服务间数据缓存 微服务多级缓存_nginx_36

六、OpenResty中实现查询Redis

现在,Redis缓存已经准备就绪,我们可以再OpenResty中实现查询Redis的逻辑了。如下图红框所示:

微服务间数据缓存 微服务多级缓存_nginx_37


当请求进入OpenResty之后:

  • 优先查询Redis缓存
  • 如果Redis缓存未命中,再查询Tomcat

1.封装Redis工具。学习:

OpenResty提供了操作Redis的模块,我们只要引入该模块就能直接使用。但是为了方便,我们将Redis操作封装到之前的common.lua工具库中。

修改/usr/local/openresty/lualib/common.lua文件:

1)引入Redis模块,并初始化Redis对象

-- 导入redis
local redis = require('resty.redis')
-- 初始化redis
local red = redis:new()

red:set_timeouts(1000, 1000, 1000)

set_timeouts(建立连接的时间、请求的超时时间、响应结果的时间)

微服务间数据缓存 微服务多级缓存_Nginx_38

2)封装函数,用来释放Redis连接,其实是放入连接池

-- 关闭redis连接的工具方法,其实是放入连接池
local function close_redis(red)
    local pool_max_idle_time = 10000 -- 连接的空闲时间,单位是毫秒
    local pool_size = 100 --连接池大小
    local ok, err = red:set_keepalive(pool_max_idle_time, pool_size)
    if not ok then
        ngx.log(ngx.ERR, "放入redis连接池失败: ", err)
    end
end

如果10秒钟,没有连接,我在释放连接。

3)封装函数,根据key查询Redis数据

-- 查询redis的方法 ip和port是redis地址,key是查询的key
local function read_redis(ip, port, key)
    -- 获取一个连接
    local ok, err = red:connect(ip, port)
    if not ok then
        ngx.log(ngx.ERR, "连接redis失败 : ", err)
        return nil
    end
    -- 查询redis
    local resp, err = red:get(key)
    -- 查询失败处理
    if not resp then
        ngx.log(ngx.ERR, "查询Redis失败: ", err, ", key = " , key)
    end
    --得到的数据为空处理
    if resp == ngx.null then
        resp = nil
        ngx.log(ngx.ERR, "查询Redis数据为空, key = ", key)
    end
    close_redis(red)
    return resp
end

4)导出

-- 将方法导出
local _M = {  
    read_http = read_http,
    read_redis = read_redis
}  
return _M
完整的common.lua:
-- 导入redis
local redis = require('resty.redis')
-- 初始化redis
local red = redis:new()
red:set_timeouts(1000, 1000, 1000)

-- 关闭redis连接的工具方法,其实是放入连接池
local function close_redis(red)
    local pool_max_idle_time = 10000 -- 连接的空闲时间,单位是毫秒
    local pool_size = 100 --连接池大小
    local ok, err = red:set_keepalive(pool_max_idle_time, pool_size)
    if not ok then
        ngx.log(ngx.ERR, "放入redis连接池失败: ", err)
    end
end

-- 查询redis的方法 ip和port是redis地址,key是查询的key
local function read_redis(ip, port, key)
    -- 获取一个连接
    local ok, err = red:connect(ip, port)
    if not ok then
        ngx.log(ngx.ERR, "连接redis失败 : ", err)
        return nil
    end
    -- 查询redis
    local resp, err = red:get(key)
    -- 查询失败处理
    if not resp then
        ngx.log(ngx.ERR, "查询Redis失败: ", err, ", key = " , key)
    end
    --得到的数据为空处理
    if resp == ngx.null then
        resp = nil
        ngx.log(ngx.ERR, "查询Redis数据为空, key = ", key)
    end
    close_redis(red)
    return resp
end

-- 封装函数,发送http请求,并解析响应
local function read_http(path, params)
    local resp = ngx.location.capture(path,{
        method = ngx.HTTP_GET,
        args = params,
    })
    if not resp then
        -- 记录错误信息,返回404
        ngx.log(ngx.ERR, "http查询失败, path: ", path , ", args: ", args)
        ngx.exit(404)
    end
    return resp.body
end
-- 将方法导出
local _M = {  
    read_http = read_http,
    read_redis = read_redis
}  
return _M

2.实现Redis查询。

接下来,我们就可以去修改item.lua文件,实现对Redis的查询了。

查询逻辑是:

  • 根据id查询Redis
  • 如果查询失败则继续查询Tomcat
  • 将查询结果返回

1)修改/usr/local/openresty/lua/item.lua文件,添加一个查询函数:

-- 导入common函数库
local common = require('common')
local read_http = common.read_http
local read_redis = common.read_redis
-- 封装查询函数
function read_data(key, path, params)
    -- 查询本地缓存
    local val = read_redis("127.0.0.1", 6379, key)
    -- 判断查询结果
    if not val then
        ngx.log(ngx.ERR, "redis查询失败,尝试查询http, key: ", key)
        -- redis查询失败,去查询http
        val = read_http(path, params)
    end
    -- 返回数据
    return val
end

2)而后修改商品查询、库存查询的业务:

微服务间数据缓存 微服务多级缓存_nginx_39


3)完整的item.lua代码:

-- 导入common函数库
local common = require('common')
local read_http = common.read_http
local read_redis = common.read_redis
-- 导入cjson库
local cjson = require('cjson')

-- 封装查询函数
function read_data(key, path, params)
    -- 查询本地缓存
    local val = read_redis("127.0.0.1", 6379, key)
    -- 判断查询结果
    if not val then
        ngx.log(ngx.ERR, "redis查询失败,尝试查询http, key: ", key)
        -- redis查询失败,去查询http
        val = read_http(path, params)
    end
    -- 返回数据
    return val
end

-- 获取路径参数
local id = ngx.var[1]

-- 查询商品信息
local itemJSON = read_data("item:id:" .. id,  "/item/" .. id, nil)
-- 查询库存信息
local stockJSON = read_data("item:stock:id:" .. id, "/item/stock/" .. id, nil)

-- JSON转化为lua的table
local item = cjson.decode(itemJSON)
local stock = cjson.decode(stockJSON)
-- 组合数据
item.stock = stock.stock
item.sold = stock.sold

-- 把item序列化为json 返回结果
ngx.say(cjson.encode(item))

3.测试:

现在停掉Tomcat服务,刷新页面,也依旧能出现数据:

说明数据是从redis中查询出来的。

微服务间数据缓存 微服务多级缓存_微服务间数据缓存_40

七、Nginx本地缓存【在OpenResty添加本地缓存】

前面以及实现了:

  1. Tomcat集群JVM缓存
  2. 实现了OPenResty到Tomca负载均衡远程调用。
  3. 实现了先查询Redis,若未命中,在查询Tomcat
  4. Openresty也搭建起来了。那么就差在Nginx中添加本地缓存
    当请求来了以后,应该优先查本地缓存,未命中后再查、reids、Tomcat、mysql

1.本地缓存API

OpenResty为Nginx提供了shard dict的功能【共享词典】,可以在nginx的多个worker进程之间共享数据,实现缓存功能。

在Nginx中往往一个master进程和多个worker进程,多个worker进程可以处理用户的请求,他们可以在单个Nginx内部做共享、共享内存。如果是多台Nginx之间是不可以共享的。

1)开启共享字典,在/usr/local/openresty/nginx/conf/nginx.conf的http下添加配置:

# 共享字典,也就是本地缓存,名称叫做:item_cache 【商品的缓存】,大小150m兆
 lua_shared_dict item_cache 150m;

2)例子:操作共享字典:

-- 获取本地缓存对象
local item_cache = ngx.shared.item_cache
-- 存储, 指定key、value、过期时间,单位s,过期自动删除。
-- 默认为0代表永不过期
item_cache:set('key', 'value', 1000)
-- 读取
local val = item_cache:get('key')

4.7.2.实现本地缓存查询

微服务间数据缓存 微服务多级缓存_springboot_41

1)修改/usr/local/openresty/lua/item.lua文件,修改read_data查询函数,添加本地缓存逻辑:

-- 导入共享词典,本地缓存
local item_cache = ngx.shared.item_cache

-- 封装查询函数
function read_data(key, expire, path, params)
    -- 查询本地缓存
    local val = item_cache:get(key)
    if not val then
        ngx.log(ngx.ERR, "本地缓存查询失败,尝试查询Redis, key: ", key)
        -- 查询redis
        val = read_redis("127.0.0.1", 6379, key)
        -- 判断查询结果
        if not val then
            ngx.log(ngx.ERR, "redis查询失败,尝试查询http, key: ", key)
            -- redis查询失败,去查询http
            val = read_http(path, params)
        end
    end
    -- 查询成功,把数据写入本地缓存
    item_cache:set(key, val, expire)
    -- 返回数据
    return val
end

2)修改item.lua中查询商品和库存的业务,实现最新的read_data函数:

微服务间数据缓存 微服务多级缓存_Nginx_42

其实就是多了缓存时间参数,过期后nginx缓存会自动删除,下次访问即可更新缓存。

这里给商品基本信息设置超时时间为30分钟,库存为1分钟。

因为库存更新频率较高,如果缓存时间过长,可能与数据库差异较大。

3)完整的item.lua文件:

-- 导入common函数库
local common = require('common')
local read_http = common.read_http
local read_redis = common.read_redis
-- 导入cjson库
local cjson = require('cjson')
-- 导入共享词典,本地缓存
local item_cache = ngx.shared.item_cache

-- 封装查询函数
function read_data(key, expire, path, params)
    -- 查询本地缓存
    local val = item_cache:get(key)
    if not val then
        ngx.log(ngx.ERR, "本地缓存查询失败,尝试查询Redis, key: ", key)
        -- 查询redis
        val = read_redis("127.0.0.1", 6379, key)
        -- 判断查询结果
        if not val then
            ngx.log(ngx.ERR, "redis查询失败,尝试查询http, key: ", key)
            -- redis查询失败,去查询http
            val = read_http(path, params)
        end
    end
    -- 查询成功,把数据写入本地缓存
    item_cache:set(key, val, expire)
    -- 返回数据
    return val
end

-- 获取路径参数
local id = ngx.var[1]

-- 查询商品信息
local itemJSON = read_data("item:id:" .. id, 1800,  "/item/" .. id, nil)
-- 查询库存信息
local stockJSON = read_data("item:stock:id:" .. id, 60, "/item/stock/" .. id, nil)

-- JSON转化为lua的table
local item = cjson.decode(itemJSON)
local stock = cjson.decode(stockJSON)
-- 组合数据
item.stock = stock.stock
item.sold = stock.sold

-- 把item序列化为json 返回结果
ngx.say(cjson.encode(item))

测试:

[root@localhost logs]# pwd
/usr/local/openresty/nginx/logs
[root@localhost logs]# tail -f error.log

查看日志:

当第一次查询某个商品时,先从本次获取,如果获取不到,就会去redis去查。如果redis查不到就会去Tomcat查缓存。

微服务间数据缓存 微服务多级缓存_Nginx_43

可以看到本地缓存速度非常快。

微服务间数据缓存 微服务多级缓存_springboot_44