当前位置:网站首页>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 .
边栏推荐
- Meta force force meta universe system development fossage model
- Preparing for the interview and sharing experience
- ISO 26262 - considerations other than requirements based testing
- How to turn on win11 game mode? How to turn on game mode in win11
- Embedded development: how to choose the right RTOS for the project?
- An in-depth understanding of fp/fn/precision/recall
- What if the win11u disk does not display? Solution to failure of win11 plug-in USB flash disk
- Jerry's manual matching method [chapter]
- Hdu4876zcc love cards (multi check questions)
- Lingyun going to sea | saihe & Huawei cloud: jointly help the sustainable development of cross-border e-commerce industry
猜你喜欢
大数据开源项目,一站式全自动化全生命周期运维管家ChengYing(承影)走向何方?
Restapi version control strategy [eolink translation]
使用 CustomPaint 绘制基本图形
Solve the problem of using uni app mediaerror mediaerror errorcode -5
Kirin Xin'an operating system derivative solution | storage multipath management system, effectively improving the reliability of data transmission
嵌入式开发:如何为项目选择合适的RTOS?
Validutil, "Rethinking the setting of semi supervised learning on graphs"
L2:ZK-Rollup的现状,前景和痛点
Cv2.resize function reports an error: error: (-215:assertion failed) func= 0 in function ‘cv::hal::resize‘
Ten thousand word summary data storage, three knowledge points
随机推荐
Backup tidb cluster to persistent volume
Redis - basic use (key, string, list, set, Zset, hash, geo, bitmap, hyperloglog, transaction)
Default constraint and zero fill constraint of MySQL constraint
Magic weapon - sensitive file discovery tool
Jerry's fast pairing does not support canceling pairing [article]
FatMouse' Trade (Hangdian 1009)
Prometheus remote_ write InfluxDB,unable to parse authentication credentials,authorization failed
Wechat official account oauth2.0 authorizes login and displays user information
cv2.resize函数报错:error: (-215:Assertion failed) func != 0 in function ‘cv::hal::resize‘
How to make agile digital transformation strategy for manufacturing enterprises
The latest Android interview collection, Android video extraction audio
Static test tool
L'enregistreur de disque dur NVR est connecté à easycvr par le Protocole GB 28181. Quelle est la raison pour laquelle l'information sur le canal de l'appareil n'est pas affichée?
201215-03-19 - cocos2dx memory management - specific explanation "recommended collection"
Jenkins user rights management
ByteDance Android interview, summary of knowledge points + analysis of interview questions
ISO 26262 - considerations other than requirements based testing
UVA 11080 – place the guards
L2: current situation, prospects and pain points of ZK Rollup
Devil daddy A0 English zero foundation self-improvement Road