天天看點

事務手動送出和XA事務問題及思考

一、背景

今天@無聊之園提出 一個問題 “手動将多個資料庫事務送出和XA效果類似,比如事務A,事務B一起送出,前面報錯就一起復原,否則一起先後執行送出”。除非是送出的時候會有失敗的可能,否則沒有問題。引發了技術群裡進行了一番探讨。

那麼事務送出的時候會失敗嗎?哪些情況下會失敗??

XA事務的目的是啥,使用場景是啥?

通過這些對我們的學習和求職又能夠帶來何種啟發?

二、研究

2.1 SOF上一個類似的問題 “Can a COMMIT statement (in SQL) ever fail? How?”

https://stackoverflow.com/questions/3960189/can-a-commit-statement-in-sql-ever-fail-how

OMMIT may fail. You might have had sufficent resources to log all the changes you wished to make, but lack resources to actually implement the changes.

And that's not considering other reasons it might fail:

The change itself might not fit the constraints of the database.

Power loss stops things from completing.

The level of requested selection concurrency might disallow an update (cursors updating a modified table, for example).

The commit might time out or be on a connection which times out due to starvation issues.

The network connection between the client and the database may be lost.

And all the other "simple" reasons that aren't on the top of my head.

列舉了五幾種情況,其中包括不符合資料庫的限制,斷電,并發更新問題,送出逾時,網絡中斷等。

《org.hibernate.TransactionException: commit failed》更是印證了這個說法。

2.3 事務被kill

之前開發的時候公司運維系統對超過某個執行時間的線程就會kill掉。

假如這個時候第一個事務送出成功後第二個事務還沒來得及送出就被kill,顯然也會送出失敗。

是以手動多個事務一起送出不太靠譜,無法可靠的保證事務的一緻性。

三、延伸

3.1 XA事務相關好文

《XA 事務處理》

https://www.infoq.cn/article/xa-transactions-handle

對XA事務給出了詳細的講解。

X/Open XA 接口是雙向的系統接口,在事務管理器以及一個或多個資料總管之間形成通信橋梁。

事務管理器控制着 JTA 事務,管理事務生命周期,并協調資源。在 JTA 中,事務管理器抽象為 javax.transaction.TransactionManager 接口,并通過底層事務服務(即 JTS)實作。

資料總管負責控制和管理實際資源(如資料庫或 JMS 隊列)。

下圖說明了事務管理器、資料總管,以及典型 JTA 環境中用戶端應用之間的關系:

————————————————

版權聲明:本文為CSDN部落客「明明如月學長」的原創文章,遵循CC 4.0 BY-SA版權協定,轉載請附上原文出處連結及本聲明。

原文連結:

https://blog.csdn.net/w605283073/article/details/91407315