全局事務/分布式事務 (Global Transaction/ A distributed transaction)之我見


這里參考的是Oracle對於XA的支持,其他的應該雷同吧。。。

 

1個分布式事務由多個行為在不同的數據庫上執行,1個分布式事務的執行成功意味着相關數據庫上的行為執行均成功。“XA協定”(http://www.opengroup.org/public/pubs/catalog/c193.htm)就支持分布式的事務,具備能力,讓多個獨立的事務資源參加全局的事務。事務資源通常是RDBMSs,不過也可以是其它種類的資源。

 

一個典型的全局性事務的架構如下,通常來說TM會集成在Application Server(例如weblogic server)中。這種TM也叫做external TM,區別於在MySQL DBMS或者Oracle DBMS中的管理本地事務的TM

 

 

 

資源管理器(RM):用戶提供通向事務的途徑。數據庫服務器(例如上面的Oracal DBMS)是一個種資源管理器。該管理器必須提交or回滾由RM管理的事務。

事務管理器(TM):用於協調作為一個分布式事務的一部分事務。通常XA的相關操作都在這里進行,而對於Client而言是透明的,TM(或許是個進程)通常是由TPM( transaction processing monitor,Texudo就有這個組件,所以Texudo也就本能地支持了全局事務)提供。

 

對於Client App而言,所有的Global Transaction都應該通過TM進行(在ORACLE中,是名字為TX的一組接口函數),TM再與RM通過XA接口(Oracle有提供這組函數)進行接洽。而所有的普通的針對同一個數據庫的事務可以直接通過Native Interface進行。

 

在Oracle的文檔里,一個Global Transaction被分為多個Branch。A branch is a unit of work contained within one RM. In the case of Oracle Database, each branch maps to a local transaction inside the database server.

 

理解全局性事務的關鍵是理解兩階段提交:

The Oracle XA library interface follows the two-phase commit protocol. The sequence of events is as follows:

  1. In the prepare phase, the TM asks each RM to guarantee that it can commit any part of the transaction. If this is possible, then the RM records its prepared state and replies affirmatively to the TM. If it is not possible, then the RM may roll back any work, reply negatively to the TM, and forget about the transaction. The protocol allows the application, or any RM, to roll back the transaction unilaterally until the prepare phase completes.
  2. In phase two, the TM records the commit decision and issues a commit or rollback to all RMs participating in the transaction. TM can issue a commit for an RM only if all RMs have replied affirmatively to phase one.

 

下面的一個例子是從Oracle的JDBC文檔里搞出來的。基本上講清楚了整個過程。特別注意的是,Note that for simplicity, this example combines code that would typically be in a middle tier with code that would typically be in a transaction manager (such as the XA resource method invocations and the creation of transaction IDs).

Oracle XA Code Sample 最底下一段

 

關於MySQL全局性事務的一些限制,http://jishu.zol.com.cn/4306.html和http://blog.sina.com.cn/s/blog_4673e6030101c7o4.html

 

一些疑問

對於MySQL的XA支持,如果在XA START/END之間的SQL語句掛了,作為RM的MySQL如何通知TM?提供的方法里只有XA PREPARE,在我的理解里,這個是用於表示第一階段的提交成功了,於是TM就可以通過查看XA RECOVER看到PREPARE狀態了。那么如何表示失敗呢?超時總不太靠譜吧?

 

 

參考

http://docs.oracle.com/cd/B19306_01/appdev.102/b14251/adfns_xa.htm#g1017655

http://docs.oracle.com/cd/B10500_01/java.920/a96654/xadistra.htm

http://liuhaodba.blog.51cto.com/6379925/1117647

http://www.iteedu.com/database/mysql/mysqlmanualcn/sql-syntax/xa.php

http://jishu.zol.com.cn/4306.html

http://blog.sina.com.cn/s/blog_4673e6030101c7o4.html

http://blog.csdn.net/mchdba/article/details/13076803


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM