五、分支事务register和report

所有文章

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,然后修改对应的状态。

猜你喜欢

转载自www.cnblogs.com/lay2017/p/12507747.html