当前位置:网站首页>Some optimization for seckill project
Some optimization for seckill project
2022-06-13 07:29:00 【Zhao JC】
seckill
Did a second kill project , And it has been optimized !
Business logic
Database design
- Why build a separate watch for second kill products ( Stopwatch ) Instead of adding a field to the product table , Because today may be a second kill , Tomorrow might be 9.9 Free shipping , In this way, the commodity table becomes more and more difficult to maintain

Some global configurations
- Global exception handling

- Error message description

JSR303 Parameter validation ( cell-phone number )
Use JSR Verify the parameters ( Take the mobile phone number as an example )



Sign in
use ThreadLocal Store user information , Ensure the safety of users in the case of multithreading ( Receive a request , And it is a request until it is completed ( One thread ) So use ThreadLocal)

Product page 、 Product details page You need to determine session State so we implement a ArgumentResolver(controller With many parameters (Respone、Request), The framework will call back this ArgumentResolvers Method , Traverse controller And assign values )

Do login verification , Sometimes the mobile terminal token It's not on cookie In the transfer , Instead, it is passed directly in the parameter ( Compatibility )

The seckill scenario is definitely not a server : The first user session On the first server , The second time the user logs in session On the second server , This leads to session invalid , So you need to use a redis Manage our... Separately session( Distributed session)


- But in the container session The expiration rule is the last access time plus the expiration time , So we need to reset cookie

Distributed Session problem ?
Internet companies in order to support greater traffic , The back-end often needs polymorphic servers to support the front-end user requests , So if the user A Server logged in , At the second request, I went to the service B There will be login failure
Distributed Session There are generally several solutions :
- Client storage : Store information directly in cookie in ,cookie Is a small piece of data stored on the client , Client pass http Agreement to proceed cookie Interaction , It is usually used to store some insensitive information
- Session Copy : On any server Session Change ( Additions and deletions ) This node will send this Session All content serialization for , Then broadcast to all other nodes
- share session: The user's Session And other information using caching middleware ( for example Redis) To unify management , Ensure that the corresponding results distributed to each server are consistent
Sharing is recommended Session The plan
seckill
Seckill is mainly divided into the following steps
First step : Judge whether the commodity inventory is sufficient
The second step : Judge whether it has been killed in seconds

The following three steps are atomic operations , It needs to be done in a transaction
The third step : Reduce inventory
Step four : Place the order
Step five : Write a second kill order 

The solution to the oversold problem
- Database with unique index : Prevent users from buying again

- SQL Add inventory quantity to judge : Prevent inventory from becoming negative

Optimize
Before optimization QPS:5000x10 1306
After optimization QPS:5000x10 2260 The core idea of optimization is : Reduce access to data
There is no database / table design .
Cache optimization
Redis Encapsulation
- Use JedisPool Pooling technology is convenient for multiple use , Also on Redis encapsulate , Easy to use

- redis One key Get one value, Only string Come and be key Is not conducive to maintenance , So the corresponding prefix is introduced keyPrefix, Each module corresponds to its own keyPrefix Easy to manage , It can be distinguished by the variables of its own module


Page caching
Put the whole page in Redis Medium cache , Reduce the number of queries to the database and page rendering
Fetch cache

Manual rendering template ( Use ThymeleafViewResolver To help us render the page manually )

- Results output

Object caching
Cache the seckill user's object , Easy to use 
Client cache ( Page static + Fore and aft end separation )
No longer use thymeleaf, While using AJAX and jQuery( The advanced ones are vue.js)


Interface optimization
use rabbitmq Change synchronous order to asynchronous order
- System initialization , Load the stock of goods into Redis in ( Realization InitializingBean Interface , rewrite afterPropertiesSet Load inventory of items into Redis In cache )

- Receive a request ,Redis Reduce stock in advance , Insufficient inventory , Go straight back to , Otherwise, enter the queue ( But if many requests come at once , If there is 10 individual , But one time came 100 A request ,11 All future requests go back to pre reduce inventory , But at this time, the inventory has been 0 了 , So I added a localGoodsOverMap To mark the memory to reduce the number of redis The interview of )



Enqueuing Requests , Return to queue immediately , This is not a second kill ( It's like 12306 Grab tickets , The ticket is being scrambled , Please wait , It doesn't mean you will succeed , It's also possible to fail )

Ask to leave the team , Generate order , reduce stock ( The core : Order asynchronously ) stay receive To really judge inventory 、 Create order


- Client polling , Is it a success ( Parallel operation with the previous step )


security
Clear text password twice MD5 Handle
Because it uses http agreement , Therefore, there are certain security problems in network transmission , So we used MD5 Means of encryption , But now there are many MD5 Push back to the tool , So I used it twice MD5+salt( The key ) To encrypt .
- First step : The client stores a fixed salt, After the user enters the password , use salt and MD5 The encrypted password is form The form is sent to the back end
- The second step : After the backend gets the password from the client , When using the user's own salt and MD5 Perform secondary encryption
- Store the password encrypted twice in the database


Seckill interface address hidden
Ideas : Before the second kill , First go to the request interface to get the second kill address
- The front end first obtains an arbitrary string through the back end as path(createSeckkillPath), All subsequent seckill requests need to bring this path Parameters


- Transform the second kill interface ( close pathvariable Parameters ), The back end checks the front end path And before returning to the front end path Are they the same? , If it is the same, the following logic will be executed

Interface current limiting
It uses annotations and interceptors to limit the number of accesses 

边栏推荐
- The 'yarn' item cannot be recognized as the name of a cmdlet, function, script file, or runnable program
- Socket programming 2:io reuse (select & poll & epoll)
- [vivefocus uses the wavevr plug-in to obtain handle operation events]
- Wechat applet - positioning, map display, route planning and navigation
- P1434 [SHOI2002] 滑雪 (记忆化搜索
- Nodejs file module FS
- Table access among Oracle database users
- About database: pgadmin4 editing SQL window
- 关于#etl#的问题:io.trino.jdbc.TrinoDriver
- The password does not take effect after redis is set
猜你喜欢

The biggest highlight of wwdc2022: metalfx

RT-Thread 模拟器 simulator LVGL控件:slider 控件

微隔离(MSG)

Real time lighting of websocket server based on esp32cam

Nfv basic overview

Logback log framework learning and problems

【ViveFocus使用WaveVR插件获取手柄操作事件】

Related operations under Oracle Database

Tidb data migration (DM) Introduction

量化框架backtrader之一文读懂Analyzer分析器
随机推荐
Issues related to C # delegation and events
论文笔记: 多标签学习 BP-MLL
Adding certificates to different systems
检测循环数“142857“
Un des backtraders du cadre de quantification lit l'analyseur
The biggest highlight of wwdc2022: metalfx
redis-7. Redis master-slave replication, cap, Paxos, cluster sharding cluster 02
redis-3. Redis list, set, hash, sorted_ set、skiplist
Three handshakes and four waves of TCP protocol and why------ One two pandas
Time field comparison time size in MySQL
Number of detection cycles "142857“
AQS - detailed explanation of reentrantlock source code
Reflection of C # Foundation
B. I Hate 1111 (记忆化搜索 数论
Station B crazy God notes
How idea breaks point debugging
TCP协议的三次握手过程和四次挥手过程以及为什么要这样? ------一二熊猫
RT thread simulator lvgl control: slider control
Questions about ETL: io trino. jdbc. TrinoDriver
Micro isolation (MSG)