我们希望达到的多级缓存架构如图:
其中:
windows上的nginx用来做反向代理服务,将前端的查询商品的ajax请求代理到OpenResty集群
OpenResty集群用来编写多级缓存业务
现在,商品详情页使用的是假的商品数据。不过在浏览器中,可以看到页面有发起ajax请求查询真实商品数据。
这个请求如下:
请求地址是localhost,端口是80,就被windows上安装的Nginx服务给接收到了。然后代理给了OpenResty集群:
我们需要在OpenResty中编写业务,查询商品数据并返回到浏览器。
但是这次,我们先在OpenResty接收请求,返回假的商品数据。
OpenResty的很多功能都依赖于其目录下的Lua库,需要在nginx.conf中指定依赖库的目录,并导入依赖:
1)添加对OpenResty的Lua模块的加载
修改/usr/local/openresty/nginx/conf/nginx.conf
文件,在其中的http下面,添加下面代码:
#lua 模块
lua_package_path "/usr/local/openresty/lualib/?.lua;;";
#c模块
lua_package_cpath "/usr/local/openresty/lualib/?.so;;";
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文件来决定
content_by_lua_file lua/item.lua;
}
这个监听,就类似于SpringMVC中的@GetMapping("/api/item")
做路径映射。
而content_by_lua_file lua/item.lua
则相当于调用item.lua这个文件,执行其中的业务,把结果返回给用户。相当于java中调用service。
1)在/usr/loca/openresty/nginx
目录创建文件夹:lua
2)在/usr/loca/openresty/nginx/lua
文件夹下,新建文件:item.lua
3)编写item.lua,返回假数据
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,即可看到效果: