当前位置:网站首页>03 _ Transaction isolation: why can't I see it after you change it?

03 _ Transaction isolation: why can't I see it after you change it?

2022-06-11 15:12:00 cjh-Java

When it comes to business , You must be no stranger , When dealing with databases , We always use business . The classic example is money transfer , You're going to show your friend Xiao Wang 100 Yuan , At this time, your bank card is only 100 Yuan .

There will be a series of operations in the transfer process , For example, check the balance 、 Add and subtract 、 Update balance, etc , These operations must be guaranteed to be integrated , Otherwise, after the procedure is checked , Before subtraction , You this 100 Yuan , We can take advantage of this time difference to check again , Then transfer money to another friend , If the bank is so whole , It's just a mess ? This is the time to use “ Business ” That's the concept .

Simply speaking , Transaction is to ensure a set of database operations , All or nothing , All or nothing . stay MySQL in , Transaction support is implemented at the engine level . You know now ,MySQL It's a multi engine system , But not all engines support transactions . such as MySQL Native MyISAM The engine doesn't support transactions , This is also MyISAM By InnoDB One of the important reasons for replacement .

In today's article , I will use InnoDB For example , analyse MySQL Specific implementation in transaction support , And based on the principle of the corresponding practical suggestions , I hope these cases can deepen your understanding of MySQL Understanding of the principle of affairs .

Isolation and isolation level

When it comes to business , You'd think ACID(Atomicity、Consistency、Isolation、Durability, Atomicity 、 Uniformity 、 Isolation, 、 persistence ), Let's talk about it today I, That is to say “ Isolation, ”.

When there are multiple transactions in the database executing at the same time , There may be dirty reading (dirty read)、 It can't be read repeatedly (non-repeatable read)、 Fantasy reading (phantom read) The problem of , To solve these problems , And then there is “ Isolation level ” The concept of .

Before we talk about isolation levels , First of all, you need to know , The tighter your isolation , The less efficient . So many times , We all need to find a balance between the two .SQL Standard transaction isolation levels include : Read uncommitted (read uncommitted)、 Read the submission (read committed)、 Repeatable (repeatable read) And serialization (serializable ). Let me explain to you one by one :

  • Read uncommitted means , When a transaction has not yet been committed , The changes it makes can be seen by other things .
  • Read submission means , After a transaction is committed , The changes it makes will be seen by other things .
  • Repeatable reading means , Data seen during the execution of a transaction , It is always consistent with the data seen when the transaction is started . Of course, at the level of repeatable read isolation , Uncommitted changes are also invisible to other transactions .
  • Serialization , As the name suggests, for the same line of records ,“ Write ” Will add “ Write lock ”,“ read ” Will add “ Read the lock ”. When there is a read/write lock conflict , Subsequent transactions must wait for the previous transaction to complete , In order to proceed .

among “ Read the submission ” and “ Repeatable ” It's hard to understand , So I'll use an example to illustrate these isolation levels . Suppose the data sheet T There is only one column , The value of one of the lines is 1, Here is the behavior of executing two transactions in chronological order .

mysql> create table T(c int) engine=InnoDB;
insert into T(c) values(1);


Let's look at the different levels of isolation , Business A What are the different return results , In the picture V1、V2、V3 What are the return values of .

  • If isolation level is “ Read uncommitted ”, be V1 The value is 2. It's time for business B Although not yet submitted , But the result has been A I saw it . therefore ,V2、V3 All of them are 2.
  • If isolation level is “ Read the submission ”, be V1 yes 1,V2 The value of is 2. Business B Can't be updated until it's submitted A notice . therefore , V3 The value of is also 2.
  • If isolation level is “ Repeatable ”, be V1、V2 yes 1,V3 yes 2. The reason V2 still 1, That's what we're following : The data that the transaction sees during execution must be consistent before and after .
  • If isolation level is “ Serialization ”, It's business B perform “ take 1 Change to 2” When , Will be locked . Until transaction A After submission , Business B To continue . So from A From the perspective of , V1、V2 The value is 1,V3 The value of is 2.

On the implementation , A view will be created in the database , When accessing, the logical result of the view shall prevail . stay “ Repeatable ” Under isolation level , This view is created when the transaction starts , This view is used throughout the life of the transaction . stay “ Read the submission ” Under isolation level , This view is in each SQL Created when the statement begins execution . What needs to be noted here is ,“ Read uncommitted ” Directly return the latest value on the record under isolation level , There is no view concept ; and “ Serialization ” Under isolation level, lock is used to avoid parallel access .

We can see under different isolation levels , Database behavior is different .Oracle The default isolation level of a database is “ Read the submission ”, So for some from Oracle Migrate to MySQL Application , To ensure the consistency of database isolation level , You must remember to MySQL The isolation level of is set to “ Read the submission ”.

The configuration is , Will start parameters transaction-isolation The value of is set to READ-COMMITTED. You can use it. show variables To see the current value .

mysql> show variables like 'transaction_isolation';

±----------------------±---------------+

| Variable_name | Value |

±----------------------±---------------+

| transaction_isolation | READ-COMMITTED |

±----------------------±---------------+

In conclusion , Existence is reason , Each isolation level has its own usage scenarios , You have to decide according to your business situation . I think You might ask when you need it “ Repeatable ” What about the scene ? Let's look at a case of data proofreading logic .

Suppose you're managing a personal bank account table . A table keeps the account balance , A table keeps the bill details . At the end of the month, you have to do data proofreading , That is to judge the difference between the balance of last month and the current balance , Is it consistent with the bill details of this month . You must hope that in the process of school alignment , Even if there's a new deal for a user , It doesn't affect your proofreading .

Use at this time “ Repeatable ” Isolation level is very convenient . The view at transaction startup can be considered static , Not affected by other transaction updates .

Implementation of transaction isolation

Understand the isolation level of transactions , Let's see how transaction isolation is implemented . Let's expand the explanation here “ Repeatable ”.

stay MySQL in , In fact, each record will record a rollback operation at the same time when it is updated . The latest value on the record , By rolling back operations , Can get the value of the previous state .

Suppose a value from 1 Has been changed in order to 2、3、4, In the rollback log, there will be records like the following .



The current value is 4, But when looking up this record , There will be different transactions started at different times read-view. As you can see in the picture , In view A、B、C Inside , The values of this record are 1、2、4, There can be multiple versions of the same record in the system , It's multi version concurrency control of database (MVCC). about read-view A, In order to get 1, You must execute all the rollback operations in the figure to get the current value .

At the same time, you will find , Even if there's another transaction going on right now 4 Change to 5, This business follows read-view A、B、C The corresponding transactions will not conflict .

You must ask , The rollback log cannot be kept all the time , When to delete ? The answer is , Delete when not needed . in other words , The system will judge , When no more transactions need to use these rollback logs , The rollback log will be deleted .

When is it not needed ? When there is no earlier rollback log in the system read-view When .

Based on the above description , Let's discuss why we suggest you try not to use long transactions .

Long transactions mean that there will be a very old transaction view in the system . Since these transactions may access any data in the database at any time , So before this transaction is committed , All possible rollback records in the database must be kept , This can lead to a lot of storage space .

stay MySQL 5.5 And previous versions , The rollback log is placed with the data dictionary ibdata In the file , Even if the long transaction is finally committed , Rollback segments are cleaned up , And the files won't get smaller . I've seen data only 20GB, And the rollback segment has 200GB The library of . Finally, we have to clean up the rollback segment , Rebuild the entire library .

In addition to the impact on rollback segments , Long transactions also take up lock resources , It could also drag down the entire warehouse , We will expand the lock later .

How to start a transaction

As described above , Long affairs have these potential risks , Of course, I suggest you try to avoid . In fact, a lot of business development students do not intend to use long Affairs , Usually due to misuse .MySQL There are several ways to start a transaction :

    • Start the transaction statement explicitly , begin or start transaction. The accompanying commit statement is commit, The rollback statement is rollback.

    • set autocommit=0, This command will turn off the automatic submission of this thread . It means if you only execute one select sentence , This transaction starts , And it doesn't automatically commit . This business continues until you take the initiative to commit or rollback sentence , Or disconnect .

    • Some client connection frameworks will default to one after successful connection set autocommit=0 The order of . This results in the following queries being in the transaction , If it's a long connection , It leads to an unexpected long affair .

      therefore , I would suggest that you always use set autocommit=1, Start the transaction through an explicit statement .

      But some development students will struggle “ One more interaction ” The problem of . For a business that requires frequent use of transactions , The second way is that each transaction does not need to be actively executed once at the beginning “begin”, Reduce the number of statement interactions . If you have that concern , I suggest you use commit work and chain grammar .

      stay autocommit by 1 Under the circumstances , use begin Explicitly started transactions , If you execute commit Then commit the transaction . If you execute commit work and chain, Commit the transaction and start the next transaction automatically , This also saves the need to execute again begin Statement overhead . At the same time, the benefit is to know clearly whether each statement is in a transaction from the perspective of program development .

      You can information_schema Library innodb_trx Query long transactions in this table , Take the following statement , Used to find a duration greater than 60s The business of .

      select * from information_schema.innodb_trx where TIME_TO_SEC(timediff(now(),trx_started))>60
      

      Summary

      In this article , I introduced MySQL The phenomenon and implementation of transaction isolation level , According to the principle of implementation, the risk of long transaction is analyzed , And how to avoid long transactions in the right way . I hope that the examples I give can help you understand the business , And better use MySQL The transactional nature of .

    原网站

    版权声明
    本文为[cjh-Java]所创,转载请带上原文链接,感谢
    https://yzsam.com/2022/162/202206111507484490.html