3 (mysql real) transaction isolation

Mentioned transaction, you certainly do not unfamiliar, and when dealing with databases, we always use the services. The most classic example is the transfer, you give a friend Wang turn 100 dollars, at a time when your bank card is only 100 dollars.

Transfer process specific to the program there will be a series of operations such as balance inquiries, to add and subtract, update balances, these operations must be guaranteed to be one, or wait until the program after finishing up, not subtraction, you 100 money, can take this time difference and then check once, and then give another friend transfers, so if the whole bank, not to mess it? Then you should use the concept of "transaction" was.

In simple terms, the transaction is to ensure a set of database operations either all succeed, or all fail. In MySQL transaction support is implemented in the engine layer. You know, MySQL is a multi-engine system support, but not all engines support transactions. For example, the native MySQL MyISAM engine does not support transactions, this is MyISAM InnoDB substituted one important reason.

Today's article, I'm going to InnoDB for example, analysis of a particular implementation in MySQL support transactions, and the corresponding practical advice based on the principle, we hope these cases can deepen your understanding of the principles MySQL affairs.

Isolation and isolation level

Mentioned transaction, you would certainly think ACID (Atomicity, Consistency, Isolation, Durability, namely atomicity, consistency, isolation, durability), today we are concerned that in which I, that is, "isolation."

When there are multiple transactions simultaneously performed on the database, it may appear dirty read (dirty read), non-repeatable read (non-repeatable read), phantom read (phantom read) the problem in order to solve these problems, there is a " the concept of isolation level ".

Before talking about the isolation level, you must first know that you isolate the more tight, the lower the efficiency. So many times, we have to find a balance between the two. SQL standard transaction isolation level comprising: Uncommitted Read (read uncommitted), Read Committed (read committed), repeatable read (repeatable read) and serialized (serializable). Let me explain one by one for you:

  • Read uncommitted means that, when a transaction is not submitted, it can be seen changes do other transactions.

  • Reading submission refers, after a transaction commits, it does change will be seen by other transactions.

  • Repeatable read refers to the process of executing a transaction to see the data, always with this transaction see when you start the data is consistent. Of course, under Repeatable Read isolation level, uncommitted change to other transactions is not visible.

  • Serialization, as the name suggests is a record for the same line, "write" will add "write lock", "read" will be added "read lock." When the read-write lock conflict occurs, the transaction must wait before the visit of a completed transaction execution can not proceed.

  • Summarized as follows:

    • Read Uncommitted: The transaction data of others changed yet, I can read in my affairs.

    • Read Submitted: Transaction data has been submitted to change the others, I can read in my affairs.

    • Repeatable read: data change other people's affairs has been submitted, I do not read in my affairs.

    • Serial: my business yet, others will not try to change data.

The "read committed" and "repeatable read" more difficult to understand, so I used a few examples to illustrate this isolation level. Assumed that the data is only one table T, which row is 1, the following acts are performed in chronological order of the two transactions.

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

We take a look at different isolation levels, transaction A which have different return results, but also is the figure inside V1, V2, V3 return value of what were yes.

  • If the isolation level is "read uncommitted", the value of V1 is 2. This time transaction B, although not yet submitted, but the results have been seen A. Therefore, V2, V3 are also 2.
  • If the isolation level is "read committed", the V1 is the value of 1, V2 is 2. B's update transaction in order to be seen after submitting A. Therefore, the value of V3 is 2.
  • If the isolation level is "repeatable read", V1, V2 is 1, V3 is 2. The reason why V2 or 1, this requirement is followed by: data before and after the transaction during the execution of seeing must be consistent.
  • If the isolation level is "serialized", it executes a transaction B "will be changed to 1 2" when will be locked. A submission until after the transaction, the transaction B can continue. Therefore, from the point of view A, V1, V2 is a value 1, V3 is 2.

On implementation, which will create a database view, when access to the logical result of view prevail. Have used this period in view of "repeatable read" isolation level, this view is created when the transaction is started, the entire transaction exists. Under "read committed" isolation level, this view is created at the time of execution of each SQL statement began. It should be noted that the "read uncommitted" direct return to the latest value on record isolation level, no view concept; and "serialized" isolation level directly under the locking way to avoid concurrent access.

We can see at different isolation level, the database behavior is different. Oracle database default isolation level is actually "read committed" and therefore for some migrate from Oracle to MySQL applications, in order to ensure a consistent database isolation level, you must remember to MySQL isolation level set to 'read committed. "

Is arranged to set the value of the transaction-isolation boot parameters into READ-COMMITTED. You can use show variables to view the current value.

mysql> show variables like 'transaction_isolation';
 
+-----------------------+----------------+
 
| Variable_name | Value |
 
+-----------------------+----------------+
 
| transaction_isolation | READ-COMMITTED |
 
+-----------------------+----------------+

In conclusion, there is reasonable, which has its own isolation level usage scenarios, you have to be determined according to their own business situation. I think you might be asking what time it needs to "re-read" scene it ? Let's look at a case of logical data collation.

Suppose you manage a personal bank account table. A table kept the balance at the end of each month, a table saved Billing Details. This time you have to do proofreading data, that is, to determine the difference between the balance and the current month's balance, is consistent with the details of the bill this month. You must want proofreading process, even if the user happens sum of new transaction does not affect your proof results.

This time using the "repeatable read" isolation level is very convenient. View can be considered static, not affected by other transactions update when the transaction starts.

Transaction Isolation implementation

Understand the isolation level of the transaction, the transaction isolation we look at is how to achieve specific. Here we expand the description "repeatable read."

In MySQL, in fact, each record while recording a rollback in the update is going to be. The latest values ​​recorded by the rollback operation, the value of the previous state can be obtained.

Assuming a value of 3, 4 are sequentially changed from 1, there will be similar to the following log records to roll back inside.

当前值是 4,但是在查询这条记录的时候,不同时刻启动的事务会有不同的 read-view。如图中看到的,在视图 A、B、C 里面,这一个记录的值分别是 1、2、4,同一条记录在系统中可以存在多个版本,就是数据库的多版本并发控制(MVCC)。对于 read-view A,要得到 1,就必须将当前值依次执行图中所有的回滚操作得到。

同时你会发现,即使现在有另外一个事务正在将 4 改成 5,这个事务跟 read-view A、B、C 对应的事务是不会冲突的。

你一定会问,回滚日志总不能一直保留吧,什么时候删除呢?答案是,在不需要的时候才删除。也就是说,系统会判断,当没有事务再需要用到这些回滚日志时,回滚日志会被删除。

什么时候才不需要了呢?就是当系统里没有比这个回滚日志更早的 read-view 的时候。

基于上面的说明,我们来讨论一下为什么建议你尽量不要使用长事务。

长事务意味着系统里面会存在很老的事务视图。由于这些事务随时可能访问数据库里面的任何数据,所以这个事务提交之前,数据库里面它可能用到的回滚记录都必须保留,这就会导致大量占用存储空间。

在 MySQL 5.5 及以前的版本,回滚日志是跟数据字典一起放在 ibdata 文件里的,即使长事务最终提交,回滚段被清理,文件也不会变小。我见过数据只有 20GB,而回滚段有 200GB 的库。最终只好为了清理回滚段,重建整个库。

除了对回滚段的影响,长事务还占用锁资源,也可能拖垮整个库,这个我们会在后面讲锁的时候展开。

事务的启动方式

如前面所述,长事务有这些潜在风险,我当然是建议你尽量避免。其实很多时候业务开发同学并不是有意使用长事务,通常是由于误用所致。MySQL 的事务启动方式有以下几种:

  1. 显式启动事务语句, begin 或 start transaction。配套的提交语句是 commit,回滚语句是 rollback。
  2. set autocommit=0,这个命令会将这个线程的自动提交关掉。意味着如果你只执行一个 select 语句,这个事务就启动了,而且并不会自动提交。这个事务持续存在直到你主动执行 commit 或 rollback 语句,或者断开连接。

有些客户端连接框架会默认连接成功后先执行一个 set autocommit=0 的命令。这就导致接下来的查询都在事务中,如果是长连接,就导致了意外的长事务。

因此,我会建议你总是使用 set autocommit=1, 通过显式语句的方式来启动事务。

但是有的开发同学会纠结“多一次交互”的问题。对于一个需要频繁使用事务的业务,第二种方式每个事务在开始时都不需要主动执行一次 “begin”,减少了语句的交互次数。如果你也有这个顾虑,我建议你使用 commit work and chain 语法。

在 autocommit 为 1 的情况下,用 begin 显式启动的事务,如果执行 commit 则提交事务。如果执行 commit work and chain,则是提交事务并自动启动下一个事务,这样也省去了再次执行 begin 语句的开销。同时带来的好处是从程序开发的角度明确地知道每个语句是否处于事务中。

你可以在 information_schema 库的 innodb_trx 这个表中查询长事务,比如下面这个语句,用于查找持续时间超过 60s 的事务。

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

小结

这篇文章里面,我介绍了 MySQL 的事务隔离级别的现象和实现,根据实现原理分析了长事务存在的风险,以及如何用正确的方式避免长事务。希望我举的例子能够帮助你理解事务,并更好地使用 MySQL 的事务特性。

我给你留一个问题吧。你现在知道了系统里面应该避免长事务,如果你是业务开发负责人同时也是数据库负责人,你会有什么方案来避免出现或者处理这种情况呢?

问题时间

问题是一天一备跟一周一备的对比。

好处是“最长恢复时间”更短。

在一天一备的模式里,最坏情况下需要应用一天的 binlog。比如,你每天 0 点做一次全量备份,而要恢复出一个到昨天晚上 23 点的备份。

一周一备最坏情况就要应用一周的 binlog 了。

当然这个是有成本的,因为更频繁全量备份需要消耗更多存储空间,所以这个 RTO 是成本换来的,就需要你根据业务重要性来评估了。

Guess you like

Origin www.cnblogs.com/chenhanhao/p/12337885.html