所有文章
https://www.cnblogs.com/lay2017/p/12485081.html
正文
在閱讀數據源代理部分的代碼的時候我們提到過ConnectionProxy會在init方法里面向Server端注冊一個分支事務,當ConnectionProxy中失敗的時候,會先Server端report一個分支事務的狀態。
那么,Server端在接收到這些請求以后又是怎么處理的呢?
branchRegister
首先,我們先看看分支事務注冊的代碼。跟進DefaultCore的branchRegister方法
@Override public Long branchRegister(BranchType branchType, String resourceId, String clientId, String xid, String applicationData, String lockKeys) throws TransactionException { // 根據XID獲取GlobalSession GlobalSession globalSession = assertGlobalSessionNotNull(xid, false); return globalSession.lockAndExcute(() -> { // ... globalSession.addSessionLifecycleListener(SessionHolder.getRootSessionManager()); // 創建BranchSession BranchSession branchSession = SessionHelper.newBranchByGlobal(globalSession, branchType, resourceId,applicationData, lockKeys, clientId); // ... try { // 添加到全局事務當中 globalSession.addBranch(branchSession); } catch (RuntimeException ex) { branchSession.unlock(); // ... } // 返回分支事務的ID return branchSession.getBranchId(); }); }
刪減掉一些校驗代碼以后,branchRegister方法邏輯就很清晰了。
1)首先,獲取GlobalSession
2)創建一個BranchSession
3)將BranchSession添加到GlobalSession中
最后返回一個branchId
branchReport
除了分支注冊以外,還有分支事務狀態的上報。
我們再跟進DefaultCore的branchReport方法
@Override public void branchReport(BranchType branchType, String xid, long branchId, BranchStatus status, String applicationData) throws TransactionException { // 獲取GlobalSession GlobalSession globalSession = assertGlobalSessionNotNull(xid, true); // 獲取BranchSession BranchSession branchSession = globalSession.getBranch(branchId); globalSession.addSessionLifecycleListener(SessionHolder.getRootSessionManager()); // 修改branchSession的狀態 globalSession.changeBranchStatus(branchSession, status); }
代碼更加地簡短。就是獲取了GlobalSession然后獲取BranchSession,最后修改對應的狀態。
總結
分支事務的注冊和上報,無非就是在GlobalSession的基礎上創建BranchSession,然后修改對應的狀態。
