当前位置:网站首页>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 of filter microplate reader 2022-2028: Research Report on technology, participants, trends, market size and share
- Three methods of bean instantiation
- How can we make millions a year now?
- What is a multi domain SSL certificate?
- 2022-2028 global internal gear motor industry research and trend analysis report
- Leetcode topic [array] -40- combined sum II
- How can we make millions a year now?
- Zhongyi Antu submitted for registration: proposed to raise 600million yuan, with annual revenue of nearly 1.2 billion yuan
- RISC-V 的MMU
- Yunkang group passed the hearing: the revenue exceeded 1billion in 8 months and the profit within the period was 270Million
猜你喜欢

Interview duck interview brush question website system source code

为什呢代码没报错但是数据库里边的数据显示不出来

线上GO服务出现GC故障,我当时就急了

Rdkit | fragment decomposition of drug molecules

【kotlin】第一天

showCTF Web入门题系列

2022-2028 global boom cylinder industry research and trend analysis report

2022-2028 global section valve industry research and trend analysis report

How can we make millions a year now?

Scientific research information | national natural conclusion regulations: more than 50% of the fund balance or it will not be concluded
随机推荐
Three declaration methods of structure type
RPA (shadow knife) does not need to write code to capture the product information of an East
Zhongyi Antu submitted for registration: proposed to raise 600million yuan, with annual revenue of nearly 1.2 billion yuan
How to exit quickly if the application is stuck?
CTF show WEB10
How to make MySQL case insensitive
2022-2028 global hydrogen internal combustion engine 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
Complex four operations (23 lines of concise code)
Construct URL and Base64 download in the form of binary stream for file download
Learning Tai Chi maker esp8226 (IX) JSON data communication III
(for line breaks) differences between gets and fgets, and between puts and fputs
[UML modeling] (4) sequence diagram of UML modeling
2021-06-17 STM32F103 USART串口代码 使用固件库
Is the index of nine interview sites of ten companies invalid?
2021-06-16 STM32F103 EXTI 中断识别 使用固件库
2021-06-17 STM32F103 USART serial port code using firmware library
2022-2028 global cooling on-off valve industry research and trend analysis report
2021-07-28 STM32F103 configuration information
Global and Chinese market of horizontal drilling rigs 2022-2028: Research Report on technology, participants, trends, market size and share