当前位置:网站首页>Two kinds of updates lost and Solutions
Two kinds of updates lost and Solutions
2022-07-07 21:59:00 【fastjson_】
Let's first create a user surface ,id Primary key
CREATE TABLE `user` (
`id` int NOT NULL AUTO_INCREMENT,
`money` int DEFAULT NULL,
`version` int DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
The first type of lost updates ( Rollback lost )
A When the transaction is cancelled , Put what has been submitted B The updated data of the transaction covers . This kind of mistake can cause serious problems , It can be seen from the following account :
Time | Withdrawals A | Transfer transaction B |
T1 | begin; |
|
T2 | begin; Start business | |
T3 | select money from user where id = 1; | |
T4 | select money from user where id = 1; | |
T5 | money = 1000 + 100; | |
T6 | commit; | |
T7 | money = 1000 - 100; | |
T8 | rollback; | |
T9 | Balance restored to 1000 element ( Lost update ) |
A When the transaction is rolled back ,“ Incaution ” take B The transaction has been erased from the account .
stay MySQL database , Any isolation level does not allow the first type of update to be lost
The second kind of lost updates ( Cover lost / Two update questions )
A Transaction coverage B Data that the transaction has committed , cause B The operation of the firm is lost :
Time | Transfer transaction A | Withdrawals B |
T1 | begin; | begin; |
T2 | select money from user where id = 1; | |
T3 | select money from user where id = 1; |
|
T4 | money = 1000 + 100; update user set money=1100 where id = 1; Remittance 100 element | |
T5 | commit; | |
T6 | select money from user where id = 1; |
|
T7 | money = 1000 - 100; update user set money=900 where id = 1; Take out 100 Change the balance to 900 element | |
T8 | commit; | |
T9 | Change the balance to 900 element ( Lost update ) |
In the above example, the deposit balance is updated because the withdrawal covers the transfer , The user lost in the end 100 element , On the contrary, if the withdrawal transaction is submitted first , Then the bank will lose 100 element .
The second reason for missing updates :MySQL By default, snapshot reads are used for repeatable reads . Read the snapshot There is no way to obtain the latest data . Therefore, snapshot reading is a major reason for the loss of the second type of updates .
solve Read the snapshot : Two basic ideas , One is pessimistic lock , The other is optimistic lock ;
Simply put, it is an assumption that such a problem is of high probability , It's best to lock it at the beginning , Lest the update always fails ; Another assumption is that such a problem is of small probability , The last step is to lock it when updating , In order to avoid locking for too long and affecting other people to do relevant operations .
Pessimistic locking
Lock when reading data , This can ensure that the data read is the latest data , And will lock the record , Other things will block if they want to get locks . So the overall business process becomes : Get the lock after opening things , Then different operations are carried out according to different business scenarios
begin; Open transaction | begin; Open transaction |
select money from user where id = 1 for update; Query account balance as 1000 element | |
select money from user where id = 1 for update; Blocking ... | |
money = 1000 - 100; update user set money=900 where id = 1; Take out 100 Change the balance to 900 element | Blocking ... |
commit; | Blocking ... |
Find the data :money = 900 | |
Other operating .... |
Optimism lock
add to version Field , Record the updated version of each record , Add one to the version number after each update .
Get the version number of the line before each thing starts , Bring the version number to judge when updating .update money set money = money + 100 where id = 1 and version = The version number found
select version from user where id = 1; | |
select version from user where id = 1; | |
begin; | begin; |
money = 1000 - 100; | |
The update is successful , The number of updates is 1 | money = 1000 + 100; update user set money=1100,version = version +1 where id = 1 and version = 0; Blocking ... |
Blocking ... | |
commit | |
The update is successful , The number of updates is 0( Because another thing changed the version number, and now the version number is 1) |
summary :
Pessimistic locking b The way is through select..for update The way , This may cause other sessions to block , Optimistic lock b Method requires maintenance of one more version column .
Personal advice : Choose pessimistic locking method in the application system with few concurrent users and serious conflicts , In other cases, first of all, optimistic locking version listing .
边栏推荐
- 三元表达式、各生成式、匿名函数
- Cv2.resize function reports an error: error: (-215:assertion failed) func= 0 in function ‘cv::hal::resize‘
- Actual combat: sqlserver 2008 Extended event XML is converted to standard table format [easy to understand]
- 使用 BlocConsumer 同时构建响应式组件和监听状态
- 嵌入式开发:如何为项目选择合适的RTOS?
- Jerry's fast pairing does not support canceling pairing [article]
- 【colmap】稀疏重建转为MVSNet格式输入
- Qt编写物联网管理平台39-报警联动
- Wechat official account oauth2.0 authorizes login and displays user information
- Contour layout of margin
猜你喜欢
大数据开源项目,一站式全自动化全生命周期运维管家ChengYing(承影)走向何方?
Use camunda to do workflow design and reject operations
Jerry's manual matching method [chapter]
谈谈制造企业如何制定敏捷的数字化转型策略
South China x99 platform chicken blood tutorial
使用 BlocConsumer 同时构建响应式组件和监听状态
Tcp/ip protocol stack
Goal: do not exclude yaml syntax. Try to get started quickly
How does win11 time display the day of the week? How does win11 display the day of the week today?
Solve the problem of uni in uni app Request sent a post request without response.
随机推荐
2022 how to evaluate and select low code development platforms?
Build your own website (18)
Restapi version control strategy [eolink translation]
Actual combat: sqlserver 2008 Extended event XML is converted to standard table format [easy to understand]
Can I open a stock account directly online now? Is it safe?
Win11U盘不显示怎么办?Win11插U盘没反应的解决方法
[open source] Net ORM accessing Firebird database
L2: current situation, prospects and pain points of ZK Rollup
The difference between NPM uninstall and RM direct deletion
ByteDance Android interview, summary of knowledge points + analysis of interview questions
使用 CustomPaint 绘制基本图形
Devil daddy A0 English zero foundation self-improvement Road
Backup tidb cluster to persistent volume
Hoj 2245 planktonic triangle cell (Mathematics)
Datatable data conversion to entity
Goal: do not exclude yaml syntax. Try to get started quickly
Why can't win11 display seconds? How to solve the problem that win11 time does not display seconds?
UVA 12230 – crossing rivers (probability) "suggested collection"
What stocks can a new account holder buy? Is the stock trading account safe
Focusing on safety in 1995, Volvo will focus on safety in the field of intelligent driving and electrification in the future