当前位置:网站首页>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)]

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)]

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)]

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)]

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)]

原网站

版权声明
本文为[Hengge ~bingo]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/172/202206210755112564.html