MySQL分布式事务
2017-09-16 本文已影响43人
goodchax
MySQL/MariaDB对分布式事务的支持是根据 X/Open CAE document Distributed Transaction Processing: The XA Specification (http://www.opengroup.org/public/pubs/catalog/c193.htm) ,主要包括下面这几个语句:
xa start 'gtid'; //开始一个全局事务
xa end 'gtid'; //结束一个全局事务
xa prepare 'gtid'; //准备完成一个事务
xa commit 'gtid'; //提交
xa rollback 'gtid'; //回滚
xa recover; //恢复
例子:
mysql> xa start 'ax2';
Query OK, 0 rows affected (0.04 秒)
mysql> update user set name = '敖翔' where userid = 11;
Query OK, 1 rows affected (0.03 秒)
mysql> xa end 'ax2';
Query OK, 0 rows affected (0.05 秒)
mysql> xa prepare 'ax2';
Query OK, 0 rows affected (0.04 秒)
mysql> xa recover;
+----------+--------------+--------------+------+
| formatID | gtrid_length | bqual_length | data |
+----------+--------------+--------------+------+
| 1 | 3 | 0 | ax2 |
+----------+--------------+--------------+------+
1 行于数据集 (0.08 秒)
mysql> xa rollback 'ax2';
Query OK, 0 rows affected (0.03 秒)
如果XA事务达到PREPARED状态而且MySQL服务器宕机,当服务器重启后,能够继续处理事务。就像原本应当的那样。但是,如果客户端连接中止而服务器继续运行,服务器将回滚任何未完成的XA事务,即使该事务已达到PREPARED状态也同样。它应能提交或回滚PREPARED XA事务,但在不更改二进制日志机制的情况下不能这样。
1、不是prepare状态的事务在重连后将无法恢复
mysql> xa start 'ax2';
Query OK, 0 rows affected (0.02 sec)
Database changed
mysql> update user set name ="敖翔" where userid=11;
Query OK, 1 row affected (0.02 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> xa end 'ax2';
Query OK, 0 rows affected (0.03 sec)
mysql> quit;
Bye
mysql> xa recover;
Empty set (0.02 sec)
2、prepare状态的事务在重连后将可恢复
mysql> xa start 'ax2';
Query OK, 0 rows affected (0.03 sec)
mysql> update user set name ="敖翔" where userid=11;
Query OK, 1 row affected (0.02 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> xa end 'ax2';
Query OK, 0 rows affected (0.02 sec)
mysql> xa prepare 'ax2';
Query OK, 0 rows affected (0.03 sec)
mysql> quit;
Bye
mysql> xa recover;
+----------+--------------+--------------+------+
| formatID | gtrid_length | bqual_length | data |
+----------+--------------+--------------+------+
| 1 | 3 | 0 | ax2 |
+----------+--------------+--------------+------+
1 row in set (0.03 sec)
后续将根据mysql �xa机制实现dubbo分布式事务。