当前位置:网站首页>[redis realizes seckill service ②] solution to oversold problem
[redis realizes seckill service ②] solution to oversold problem
2022-06-25 00:44:00 【Bulst】
List of articles
In our last article , Realize the basic business of secsha , But in a concurrent scenario , We will find many problems in the code , Oversold is one of the classic problems . Let's study this thing together .
What is oversold
Oversold is a common phenomenon in seckill business , It means that the user is in the process of purchasing the specified goods , The goods sold exceeded the expectations of the merchants .
How oversold comes into being
If there is only one product left , Just then, two threads enter the red box at the same time , Will enter the updated code together , So there will be oversold .

Graphic oversold
Normal condition

Oversold 
Solution
Oversold problem is a typical multi thread security problem , A common solution to this problem is locking :
- Pessimistic locking
- Optimism lock
Pessimistic locking
Think thread safety problems are bound to happen , Therefore, obtain the lock before operating the data , Ensure that threads execute serially .
for example Synchronized、Lock All belong to pessimistic lock .
Pessimistic concurrency control is actually “ Take the lock first and then visit ” A conservative strategy , For the security of data processing .
But in terms of efficiency , The mechanism of dealing with lock will cause extra cost to the database , And increase the chance of deadlock , At the same time, it will reduce the concurrent performance .
Pessimistic lock implementation ----MySQL edition
Use pessimistic locks , We have to shut it down mysql Auto-commit properties for the database .MySQL By default autocommit Pattern , in other words , When you perform an update operation ,MySQL The results will be submitted immediately . We can use command Settings MySQL For the wrong autocommit Pattern :set autocommit=0;
// Start business
begin;
// Find out the inventory information of goods , Use for update Add the lock
select quantity from items where id=1 for update;
// Modify merchandise inventory
update items set quantity=100 where id = 1;
// Commit transaction
commit;
Optimism lock
Think thread safety problems don't necessarily happen , So don't lock , Just judge whether other threads have modified the data when updating the data .
If there is no modification, it is considered safe , Update the data yourself .
If it has been modified by other threads, it indicates that a security problem has occurred , At this point, you can retry or exception .
Compared with pessimistic lock , When processing the database , Optimistic locks do not use the lock mechanism provided by the database . The general way to implement optimistic locking is to record the data version .
Optimistic locks do not produce any locks and deadlocks , Better performance .
The realization of optimistic lock
By a single can be sequentially increasing version Field , You can avoid ABA problem :
// Search out the product information ,version = 1
select version from items where id=1
// Change the stock of goods to 2
update items set quantity=2,version = 3 where id=1 and version = 2;
except version outside , You can also use time stamps , Because timestamps are naturally sequential .
Reduce optimistic lock strength , Can maximize throughput , Improve concurrency :
// Modify merchandise inventory
update item
set quantity=quantity - 1
where id = 1 and quantity - 1 > 0
Choose pessimistic lock or optimistic lock
- Optimistic locks are not really locked , Efficient . However , If the granularity of the lock is not well controlled , The probability of update failure will be higher , Prone to business failure .
- Pessimistic lock depends on database lock , Low efficiency . The probability of update failure is low .
- In a highly concurrent business scenario , Pessimistic locks are being used less and less .
In the next chapter, we will specifically implement the optimistic lock scheme .
边栏推荐
- Domain Driven Design and coding
- Practical operation notes - notebook plus memory and ash cleaning
- 【Redis实现秒杀业务③】超卖问题之乐观锁具体实现
- A website for programmers with a monthly salary of 30K
- Xcode预览(Preview)显示List视图内容的一个Bug及解决
- What is test development? Can you find a job at this stage?
- Network request -volley
- ros(24):error: invalid initialization of reference of type ‘xx’ from expression of type ‘xx’
- Encryption and encoding resolution
- Go crawler framework -colly actual combat (II) -- Douban top250 crawling
猜你喜欢

Technologie des fenêtres coulissantes en octets dans la couche de transmission
Fuxin Kunpeng joins in, and dragon lizard community welcomes a new partner in format document technical service

Ott marketing is booming. How should businesses invest?

【Redis实现秒杀业务②】超卖问题的解决方案

Custom animation (simulated win10 loading animation)

How to quickly open traffic master for wechat applet
![[interview question] what is a transaction? What are dirty reads, unrepeatable reads, phantom reads, and how to deal with several transaction isolation levels of MySQL](/img/95/02a58c9dc97bd8347b43247e38357d.png)
[interview question] what is a transaction? What are dirty reads, unrepeatable reads, phantom reads, and how to deal with several transaction isolation levels of MySQL

2021-11-07

傳輸層 以字節為單比特的滑動窗口技術

【微服务|Sentinel】Sentinel快速入门|构建镜像|启动控制台
随机推荐
Go crawler framework -colly actual combat (IV) -- Zhihu answer crawl (I)
D does not require opapply() as a domain
Ott marketing is booming. How should businesses invest?
Basic summary of MySQL database knowledge
Working principle analysis of kubernetes architecture core components
Intensive reading of thinking about markdown
Unimportant tokens can be stopped in advance! NVIDIA proposes an efficient visual transformer network a-vit with adaptive token to improve the throughput of the model
C# Winform 最大化遮挡任务栏和全屏显示问题
Encryption and encoding resolution
Several ways for wechat applet to jump to the page are worth collecting
A website for programmers with a monthly salary of 30K
JMeter socket connection sends data
【排行榜】Carla leaderboard 排行榜 运行与参与手把手教学
C#和C 的CAN通信实验
More pictures | explain the Nacos parameters in detail!
Is it so difficult to calculate the REM size of the web page according to the design draft?
2021-04-18
Custom animation (simulated win10 loading animation) - Optimization
How can I persuade leaders to use DDD to construct the liver project?
Meta & Berkeley proposed a universal multi-scale visual transformer based on pooled self attention mechanism. The classification accuracy in Imagenet reached 88.8%! Open source