Detailed MySQL database (C) MySQL transaction isolation analysis

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 reapeatable read), phantom read (phantom read) the problem in order to solve these problems, there is a "quarantine concept 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 serialization 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.
  • The "read committed" and "repeatable read" more difficult to understand, so I used a few examples to illustrate this isolation level. It 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.

我们可以看到在不同的隔离级别下,数据库行为是有所不同的。Oracle 数据库的默认隔离级别其实就是“读提交”,因此对于一些从 Oracle 迁移到 MySQL 的应用,为保证数据库隔离级别的一致,你一定要记得将 MySQL 的隔离级别设置为“读提交”。

配置的方式是,将启动参数 transaction-isolation 的值设置成 READ-COMMITTED。你可以用show variables 来查看当前的值。

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

总结来说,存在即合理,哪个隔离级别都有它自己的使用场景,你要根据自己的业务情况来定。我想你可能会问那什么时候需要“可重复读”的场景呢?我们来看一个数据校对逻辑的案例。

假设你在管理一个个人银行账户表。一个表存了每个月月底的余额,一个表存了账单明细。这时候你要做数据校对,也就是判断上个月的余额和当前余额的差额,是否与本月的账单明细一致。

你一定希望在校对过程中,即使有用户发生了一笔新的交易,也不影响你的校对结果。这时候使用“可重复读”隔离级别就很方便。事务启动时的视图可以认为是静态的,不受其他事务更新的影响。

事务隔离的实现

理解了事务的隔离级别,我们再来看看事务隔离具体是怎么实现的。这里我们展开说明“可重复读”。

在 MySQL 中,实际上每条记录在更新的时候都会同时记录一条回滚操作。记录上的最新值,通过回滚操作,都可以得到前一个状态的值。

假设一个值从 1 被按顺序改成了 2、3、4,在回滚日志里面就会有类似下面的记录。

当前值是 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 的事务特性。

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

Guess you like

Origin www.cnblogs.com/whgk/p/11085428.html