当前位置:网站首页>Use lua+redis+openresty to realize concurrent optimization of e-commerce Homepage
Use lua+redis+openresty to realize concurrent optimization of e-commerce Homepage
2022-06-21 08:05:00 【Hengge ~bingo】
Case background
The homepage of e-commerce usually has an advertising rotation diagram , Generally, the data of the rotation chart needs to be obtained through the background interface , When the concurrency is large, it will bring pressure to the server .
The general solution is to cache the carousel map data to Redis in , This reduces access to the database .
We visit Redis Also need to use Java,Java Project deployment Tomcat in ,Tomcat The server also faces the pressure of high concurrency .
Nginx The concurrency performance of the server is much higher than Tomcat, stay Nginx Use in Lua Script can be implemented MySQL and Redis Read and write , Bypass Tomcat, Greatly improve the concurrency performance of the home page .
The case needs to use OpenResty, Reference resources :https://blog.csdn.net/u013343114/article/details/123991729
Development steps
There are two steps :
1、 Cache preheating
2、 Cache reads
Cache preheating
Use Lua Read MySQL Rotation chart data in , Save to Redis in
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-TPCS8uek-1655367724026)(Lua Optimize the home page .assets/1655365058445.png)]](/img/d5/b42b4e078f7a0b24e1b0ee9f6ee7c6.png)
ad_update.lua
-- get uri Medium sid Parameter values
local uri_args = ngx.req.get_uri_args()
local sid = uri_args["sid"]
-- Connect mysql
local mysql = require "resty.mysql"
local db = mysql:new()
db:set_timeout(1000)
local ok, err = db:connect{
host = "127.0.0.1",
port = 3306,
database = "edu_ad",
user = "root",
password = "123456",
charset = "utf8"
}
if not ok then
ngx.say("failed to connect: ", err)
return
end
ngx.say("connected to mysql.")
-- Query the rotation chart by area number
local res, err = db:query("select * from promotion_ad where space_id="..sid)
if not res then
ngx.say("bad result: ", err)
return
end
db:close()
-- The result is converted to json
local cjson = require "cjson"
ngx.say("res->",cjson.encode(res))
-- Connect redis
local redis = require "resty.redis"
local red = redis:new()
red:set_timeout(2000)
local ok,err = red:connect("127.0.0.1",6379)
if not ok then
ngx.say("connect error: ", err)
return
end
-- Save to reids
red:set("ad_space_"..sid,cjson.encode(res))
red:close()
ngx.say("updated redis")
take ad_update.lua Save to openresty/nginx/conf/lua Under the table of contents
To configure nginx.conf
server {
listen 8080;
default_type 'applicaiton/json;charset=utf8';
charset utf-8;
location /ad_update{
default_type text/html;
content_by_lua_file conf/lua/ad_update.lua;
}
}
Access test
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-16RM0inJ-1655367724042)(Lua Optimize the home page .assets/1655366388575.png)]](/img/1b/89a470e902744dc2e8e02aa9170051.png)
Cache reads
There are two levels of cache , The first level cache is nginx Internal Cache , The second level is redis cache , Read the internal cache first , If it is not read again redis cache
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-gf2FpNYm-1655367724055)(Lua Optimize the home page .assets/1655366301383.png)]](/img/c8/f30e60dd7509148a74c3edf0409744.png)
ad_load.lua
-- get sid Parameters
local uri_args = ngx.req.get_uri_args()
local sid = uri_args["sid"]
-- Read internal cache
local cache = ngx.shared.dis_cache:get('ad_space_'..sid)
if cache == nil then
-- Internal cache not read redis
local redis = require "resty.redis"
local red = redis:new()
red:set_timeout(2000)
local ok, err = red:connect("127.0.0.1", 6379)
local res = red:get('ad_space:'..sid)
ngx.say(res)
red:close()
-- Save to internal cache
ngx.shared.dis_cache:set('ad_space_'..sid, res, 10*60);
else
ngx.say(cache)
end
To configure nginx.conf
server {
listen 8080;
default_type 'applicaiton/json;charset=utf8';
charset utf-8;
location /ad_update{
default_type text/html;
content_by_lua_file conf/lua/ad_update.lua;
}
location /ad_load{
default_type text/html;
content_by_lua_file conf/lua/ad_load.lua;
}
}
stay http Module plus internal cache configuration :
lua_shared_dict dis_cache 5m;
Access test
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-juVsJGZ7-1655367724060)(Lua Optimize the home page .assets/1655366610354.png)]](/img/b9/5a569f0b9ad51bb1db30a7c02c4504.png)
home page
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> Bubble Education </title>
<link rel="stylesheet" href="css/index.css">
<!-- Introducing styles -->
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<!-- Import component library -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
</head>
<body>
<div id="app">
<!-- advertisement -->
<div style=" width:1200px; margin:0px auto; margin-top:20px;">
<el-carousel indicator-position="outside">
<el-carousel-item v-for="(item , index) in adList" :key="index">
<a :href="item.link">
<img :src="item.img" style='width: 100%;height: 100%;object-fit: cover;'/>
</a>
</el-carousel-item>
</el-carousel>
</div>
</div>
<script>
new Vue( {
el:"#app",
name: "Index",
data() {
return {
adList: []
};
},
created() {
this.getAdList();
},
methods: {
// Get top rotation ads
getAdList(){
return axios
.get("http://192.168.7.188:8080/ad_load?sid=1")
.then((result) => {
console.log(result);
this.adList = result.data;
}
).catch( (error)=>{
this.$message.error(" Failed to get the rotation advertisement !");
});
}
}
});
</script>
</body>
</html>
Deploy the network to nginx Of html Directory , Configure home page
location / {
default_type text/html;
root html/edu_learn_web;
index index.html;
}
test
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-cr9znn8B-1655367724068)(Lua Optimize the home page .assets/1655367062628.png)]](/img/68/91f8f01a6a43c46965539361d30b25.png)
边栏推荐
- Global and Chinese market for military imaging systems 2022-2028: Research Report on technology, participants, trends, market size and share
- 群暉DSM7添加套件源
- 升级Jenkins步骤和遇到的问题
- How to optimize MySQL paging query
- Is the index of nine interview sites of ten companies invalid?
- CTF show WEB10
- How can we make millions a year now?
- [redis]-[redis underlying data structure] - Dictionary
- How to view the MySQL installation path
- 2021-06-16 STM32F103 EXTI 中断识别 使用固件库
猜你喜欢

How can we make millions a year now?

WordPress website security in 2022

Illustration Google V8 15: Hidden classes: how to quickly find object attributes in memory?

How to write circular statements in MySQL stored procedures

Qunhui dsm7 add kit source

Cluster hui dsm7 add suite source

There was a GC failure in the online go service. I was in a hurry

Interview duck interview brush question website system source code

群暉DSM7添加套件源

How to write attractive titles for short videos? Learn these tips to make your title more convincing
随机推荐
Matlab 3D diagram (unconventional)
Eureka的TimedSupervisorTask类(自动调节间隔的周期性任务)
结构体类型的三种声明方式
古风排版 (20 分)(测试点4)
showCTF Web入门题系列
Global and Chinese market of electrical connectors 2022-2028: Research Report on technology, participants, trends, market size and share
MMS for risc-v
[Redis]-[Redis底层数据结构]-SDS
[visualization - source code reading] antvis / g-base interpretation - 1
2021-07-28 STM32F103 I2C Hardware Transfer Include previous IO Clock EXIT USB use firmware library
What is the MySQL database zipper table
Three declaration methods of structure type
Horizontal slot, one line of code can directly convert the web page to PDF and save it (pdfkit)
Blank screen of virtual machine browser
MySql 过滤查询(以字母开头,以数字开头,非数字开头,非字母开头)
2022-2028 global section valve industry research and trend analysis report
Global and Chinese market for diamond blades 2022-2028: Research Report on technology, participants, trends, market size and share
Illustration Google V8 14: bytecode (2): how does the interpreter interpret and execute bytecode?
华三IPsec
How MySQL closes a transaction