seata源码分析(AT)-事务提交和回滚

seata源码分析之如何控制下游服务的提交与回滚 概览 seata client跟维持了一个连接,监听server端的消息,根据接到的消息判断是提交还是回滚。 客户端建立流程: GlobalTransactionScanner.afterPropertiesSet() GlobalTransactionScanner.initClient() TMClient.init TmRpcClient.getInstance new TmRpcClient new ... 阅读详情

一、事务会回滚

在业务方法中加了@GlobalTransactional过后,开启全局事务,其实就是一个aop,这个已经说过了,现在要说的是在这个aop GlobalTransactionalInterceptor中真正的处理是先开启事务,业务逻辑的真正处理,最后根据是否抛出异常来决定是提交还是回滚,所以这里先分析回滚
在这里插入图片描述

1、客户端的回滚发起点

io.seata.tm.api.TransactionalTemplate#rollbackTransaction

private void rollbackTransaction(GlobalTransaction tx, Throwable originalException) throws TransactionException, TransactionalExecutor.ExecutionException {
    triggerBeforeRollback();
    //远程调用TC进行分布式事务的回滚
    tx.rollback();
    triggerAfterRollback();
    // 3.1 Successfully rolled back
    throw new TransactionalExecutor.ExecutionException(tx, GlobalStatus.RollbackRetrying.equals(tx.getLocalStatus())
            ? TransactionalExecutor.Code.RollbackRetrying : TransactionalExecutor.Code.RollbackDone, originalException);
}

2、服务端的处理

io.seata.server.coordinator.DefaultCoordinator#doGlobalRollback

/**
 * 分布式事务的回滚
 * @param request    the request
 * @param response   the response
 * @param rpcContext the rpc context
 * @throws TransactionException
 */
@Override
protected void doGlobalRollback(GlobalRollbackRequest request, GlobalRollbackResponse response,
                                RpcContext rpcContext) throws TransactionException {
    response.setGlobalStatus(core.rollback(request.getXid()));
}

io.seata.server.coordinator.DefaultCore#rollback

public GlobalStatus rollback(String xid) throws TransactionException {
    //注册分支事务,先通过全局事xid找到全局事务和分支事务
    //1.先通过全局事务XID找到去global_table查询到全局事务对象
    //2.通过查询出来的xid对象去查询branch_talbe是否有分支事务,最后将这两个事务对象封装到GlobalSession中
    //这里传入的true代表全局事务和分支事务都查询出来,全局事务是一条数据,分支事务可能会多条是一个list
    GlobalSession globalSession = SessionHolder.findGlobalSession(xid);
    //如果没有查询到全局事务对象,则直接返回完成
    if (globalSession == null) {
        return GlobalStatus.Finished;
    }
    globalSession.addSessionLifecycleListener(SessionHolder.getRootSessionManager());
    // just lock changeStatus
    boolean shouldRollBack = SessionHolder.lockAndExecute(globalSession, () -> {
        //设置本事务的active状态为false
        globalSession.close(); // Highlight: Firstly, close the session, then no more branch can be registered.
        //如果目前的全局事务状态为Begin开始状态,那么修改全局事务的状态为回滚中,修改数据表global_table的status的值为Rollbacking
        if (globalSession.getStatus() == GlobalStatus.Begin) {
            //修改global_table的status的值为Rollbacking
            globalSession.changeStatus(GlobalStatus.Rollbacking);
            return true;
        }
        return false;
    });
    if (!shouldRollBack) {
        return globalSession.getStatus();
    }

    //真正的回滚逻辑
    doGlobalRollback(globalSession, false);
    //返回回滚的逻辑
    return globalSession.getStatus();
}

io.seata.server.coordinator.DefaultCore#doGlobalRollback

public boolean doGlobalRollback(GlobalSession globalSession, boolean retrying) throws TransactionException {
    boolean success = true;
    // start rollback event
    eventBus.post(new GlobalTransactionEvent(globalSession.getTransactionId(), GlobalTransactionEvent.ROLE_TC,
        globalSession.getTransactionName(), globalSession.getBeginTime(), null, globalSession.getStatus()));

    if (globalSession.isSaga()) {
        success = getCore(BranchType.SAGA).doGlobalRollback(globalSession, retrying);
    } else {
        //globalSession.getReverseSortedBranches()得到的是所有分支
        for (BranchSession branchSession : globalSession.getReverseSortedBranches()) {
            BranchStatus currentBranchStatus = branchSession.getStatus();
            //如果分支事务是在一阶段失败的,调用removeBranch
            if (currentBranchStatus == BranchStatus.PhaseOne_Failed) {
                globalSession.removeBranch(branchSession);
                continue;
            }
            try {
                //branchRollback回滚分支事务,这里是server端,所以这里的分支事务的回滚是调用的远程进行回滚的
                //而远程回滚就是使用的undo log日志表来回滚的
                BranchStatus branchStatus = branchRollback(globalSession, branchSession);
                switch (branchStatus) {
                    //PhaseTwo_Rollbacked表示远程回滚成功
                    case PhaseTwo_Rollbacked:
                        //删除分支事务信息,就是删除branch_table和释放锁
                        //1.释放锁,删除lock_table中的行锁信息;
                        //2.删除分支事务,branch_table
                        globalSession.removeBranch(branchSession);
                        LOGGER.info("Rollback branch transaction successfully, xid = {} branchId = {}", globalSession.getXid(), branchSession.getBranchId());
                        continue;
                    case PhaseTwo_RollbackFailed_Unretryable:
                        //远程回滚失败,修改全局事务状态为RollbackFailed
                        SessionHelper.endRollbackFailed(globalSession);
                        LOGGER.info("Rollback branch transaction fail and stop retry, xid = {} branchId = {}", globalSession.getXid(), branchSession.getBranchId());
                        return false;
                    default:
                        LOGGER.info("Rollback branch transaction fail and will retry, xid = {} branchId = {}", globalSession.getXid(), branchSession.getBranchId());
                        if (!retrying) {
                            globalSession.queueToRetryRollback();
                        }
                        return false;
                }
            } catch (Exception ex) {
                StackTraceLogger.error(LOGGER, ex,
                    "Rollback branch transaction exception, xid = {} branchId = {} exception = {}",
                    new String[] {globalSession.getXid(), String.valueOf(branchSession.getBranchId()), ex.getMessage()});
                if (!retrying) {
                    globalSession.queueToRetryRollback();
                }
                throw new TransactionException(ex);
            }
        }

        // In db mode, there is a problem of inconsistent data in multiple copies, resulting in new branch
        // transaction registration when rolling back.
        // 1. New branch transaction and rollback branch transaction have no data association
        // 2. New branch transaction has data association with rollback branch transaction
        // The second query can solve the first problem, and if it is the second problem, it may cause a rollback
        // failure due to data changes.
        GlobalSession globalSessionTwice = SessionHolder.findGlobalSession(globalSession.getXid());
        if (globalSessionTwice != null && globalSessionTwice.hasBranch()) {
            LOGGER.info("Rollbacking global transaction is NOT done, xid = {}.", globalSession.getXid());
            return false;
        }
    }
    if (success) {
        //如果分支事务回滚成功,删除全局事务
        //1.先修改全局事务global_table的状态为Rollbacked
        //2.删除全局事务global_table
        SessionHelper.endRollbacked(globalSession);

        // rollbacked event 发布事件
        eventBus.post(new GlobalTransactionEvent(globalSession.getTransactionId(), GlobalTransactionEvent.ROLE_TC,
            globalSession.getTransactionName(), globalSession.getBeginTime(), System.currentTimeMillis(),
            globalSession.getStatus()));

        LOGGER.info("Rollback global transaction successfully, xid = {}.", globalSession.getXid());
    }
    return success;
}

简单来说:
1、获取所有的分支事务
2、远程回滚分支事务(远程回滚undo log日志);
3、删除本地分支事务branch_table和释放锁(lock_table);
4、删除全局事务。

3、客户端的回滚逻辑

客户端的netty处理器是在RMClient初始化的,RmClient是在spring自动装配注入的

com.alibaba.cloud.seata.GlobalTransactionAutoConfiguration#globalTransactionScanner
》io.seata.spring.annotation.GlobalTransactionScanner#afterPropertiesSet
》》io.seata.spring.annotation.GlobalTransactionScanner#initClient
》》》io.seata.rm.RMClient#init

public static void init(String applicationId, String transactionServiceGroup) {
    RmNettyRemotingClient rmNettyRemotingClient = RmNettyRemotingClient.getInstance(applicationId, transactionServiceGroup);
    rmNettyRemotingClient.setResourceManager(DefaultResourceManager.get());
    //设置handler处理器,DefaultRMHandler.get()是通过spi机制获取到所有的RM处理器
    //spi:io.seata.rm.AbstractRMHandler
    rmNettyRemotingClient.setTransactionMessageHandler(DefaultRMHandler.get());
    rmNettyRemotingClient.init();
}

io.seata.rm.AbstractRMHandler#doBranchRollback

/**
 * Do branch rollback.
 * 分支事务回滚
 * @param request  the request
 * @param response the response
 * @throws TransactionException the transaction exception
 */
protected void doBranchRollback(BranchRollbackRequest request, BranchRollbackResponse response)
    throws TransactionException {
    String xid = request.getXid();
    long branchId = request.getBranchId();
    String resourceId = request.getResourceId();
    String applicationData = request.getApplicationData();
    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("Branch Rollbacking: " + xid + " " + branchId + " " + resourceId);
    }
    //这里就是调用本地的逻辑,简单来说就是获取undo日志表中获取前置镜像进行回滚,然后删除undo log日志
    //里面的处理逻辑有点复杂,简单来说就是
    //1.取出undo log日志;
    //2.判断是否可以回滚,要进行对比,对比后置镜像是否和业务数据表的数据是一致的,不一致的不能回滚,证明被其他线程修改了数据;
    //3.回滚日志,根据不同操作删除、插入、修改业务数据表的数据;
    //4.最后要删除undo log日志。
    //如果回滚成功,返回状态PhaseTwo_Rollbacked
    BranchStatus status = getResourceManager().branchRollback(request.getBranchType(), xid, branchId, resourceId,
        applicationData);
    response.setXid(xid);
    response.setBranchId(branchId);
    response.setBranchStatus(status);
    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("Branch Rollbacked result: " + status);
    }
}

io.seata.rm.datasource.DataSourceManager#branchRollback

public BranchStatus branchRollback(BranchType branchType, String xid, long branchId, String resourceId,
                                   String applicationData) throws TransactionException {
    DataSourceProxy dataSourceProxy = get(resourceId);
    if (dataSourceProxy == null) {
        throw new ShouldNeverHappenException();
    }
    try {
        //分支事务回滚,这里就很简单,就是从undo log日志表里面取出要回滚的记录,也就是前置镜像进行回滚,回滚完成要删除undo log日志
        UndoLogManagerFactory.getUndoLogManager(dataSourceProxy.getDbType()).undo(dataSourceProxy, xid, branchId);
    } catch (TransactionException te) {
        StackTraceLogger.info(LOGGER, te,
            "branchRollback failed. branchType:[{}], xid:[{}], branchId:[{}], resourceId:[{}], applicationData:[{}]. reason:[{}]",
            new Object[]{branchType, xid, branchId, resourceId, applicationData, te.getMessage()});
        if (te.getCode() == TransactionExceptionCode.BranchRollbackFailed_Unretriable) {
            return BranchStatus.PhaseTwo_RollbackFailed_Unretryable;
        } else {
            return BranchStatus.PhaseTwo_RollbackFailed_Retryable;
        }
    }
    return BranchStatus.PhaseTwo_Rollbacked;

}

二、事务的提交

事务的提交入口和回滚一样,也是在拦截器GlobalTransactionalInterceptor中的,和回滚的逻辑一样,只是远程调用TC进行提交事务的处理不一样
,但是事务的提交和回滚的逻辑差别太大了,因为提交事务采用了异步处理,首先TM端发起的事务提交,TC端收到过后只是修改了事务的状态为异步提交,然后就返回给TM端了,而TC端开启了一个异步调度任务,每1s循环一次,取出所有的异步提交的事务列表,然后循环开始提交,提交的逻辑也是发送给TM端(客户端),而客户端接受到过后又放入到一个异步队列中,在TM端又开了一个异步调度线程,一直从这个队列中取出TC端发过来的提交事务对象,然后开始进行异步提交,异步提交也是批量提交,每次删除1000条分支事务,逻辑也很简单,就是删除客户端的undo log日志了。
在这里插入图片描述

1、客户端处理

io.seata.tm.api.DefaultGlobalTransaction#commit、

public void commit() throws TransactionException {
    //参与者无法进行提交,只有TM端才能进行提交
    if (role == GlobalTransactionRole.Participant) {
        // Participant has no responsibility of committing
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Ignore Commit(): just involved in global transaction [{}]", xid);
        }
        return;
    }
    assertXIDNotNull();
    //调用transactionManager.commit(xid);进行提交,提交失败可以重试
    int retry = COMMIT_RETRY_COUNT <= 0 ? DEFAULT_TM_COMMIT_RETRY_COUNT : COMMIT_RETRY_COUNT;
    try {
        while (retry > 0) {
            try {
                status = transactionManager.commit(xid);
                break;
            } catch (Throwable ex) {
                LOGGER.error("Failed to report global commit [{}],Retry Countdown: {}, reason: {}", this.getXid(), retry, ex.getMessage());
                retry--;
                if (retry == 0) {
                    throw new TransactionException("Failed to report global commit", ex);
                }
            }
        }
    } finally {
        if (xid.equals(RootContext.getXID())) {
            suspend();
        }
    }
    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("[{}] commit status: {}", xid, status);
    }
}

2、服务端的处理

2.1、服务端的异步处理点1(修改事务状态为异步提交)

io.seata.server.coordinator.DefaultCoordinator#doGlobalCommit

/**
 * 全局事务的提交
 * @param request    the request
 * @param response   the response
 * @param rpcContext the rpc context
 * @throws TransactionException
 */
@Override
protected void doGlobalCommit(GlobalCommitRequest request, GlobalCommitResponse response, RpcContext rpcContext)
    throws TransactionException {
    response.setGlobalStatus(core.commit(request.getXid()));
}

io.seata.server.coordinator.DefaultCore#commit

public GlobalStatus commit(String xid) throws TransactionException {
    /**
     * 根据xid找到全局事务对象和所有的分支事务list
     * 全局事务从global_table中查询
     * 分支事务从branch_list查询
     */
    GlobalSession globalSession = SessionHolder.findGlobalSession(xid);
    if (globalSession == null) {
        return GlobalStatus.Finished;
    }
    globalSession.addSessionLifecycleListener(SessionHolder.getRootSessionManager());
    // just lock changeStatus

    boolean shouldCommit = SessionHolder.lockAndExecute(globalSession, () -> {
        // Highlight: Firstly, close the session, then no more branch can be registered.
        //设置全局事务状态active为false
        //释放所有的分支事务锁,简单来说就是删除lock_table的行锁信息
        globalSession.closeAndClean();
        //如果当前的事务状态为开始,则开始提交事务,这里的提交事务其实不是真正的提交事务,提交事务是需要删除分支事务、全局事务和远程删除
        //客户端业务的undo log日志记录的,但是这里的提交事务只是把全局事务global_table中的事务状态修改了2次
        //第一次修改为begin(1),第二次修改为AsyncCommitting(8) 异步提交状态(?为什么这里要修改2次)
        if (globalSession.getStatus() == GlobalStatus.Begin) {
            //如果支持异步提交事务的话(AT模式默认是异步提交),那么异步提交这里只是将全局事务的状态修改为异步提交状态8
            //后面有一个线程在真正的异步提交,这个线程是DefaultCoordinator中的一个异步调度线程ScheduledThreadPoolExecutor处理的,是在init方法中初始化的
            if (globalSession.canBeCommittedAsync()) {
                //修改两次全局事务的状态
                globalSession.asyncCommit();
                return false;
            } else {
                //如果不支持异步提交,这里修改为提交状态Committing(2)
                globalSession.changeStatus(GlobalStatus.Committing);
                return true;
            }
        }
        return false;
    });

    if (shouldCommit) {
        //如果不是异步提交的事务,向远程提交一个事务提交的请求,远程接受到过后放入到队列异步提交
        boolean success = doGlobalCommit(globalSession, false);
        if (success && !globalSession.getBranchSessions().isEmpty()) {
            globalSession.asyncCommit();
            return GlobalStatus.Committed;
        } else {
            return globalSession.getStatus();
        }
    } else {
        return globalSession.getStatus() == GlobalStatus.AsyncCommitting ? GlobalStatus.Committed : globalSession.getStatus();
    }
}

io.seata.server.session.GlobalSession#asyncCommit

public void asyncCommit() throws TransactionException {
    this.addSessionLifecycleListener(SessionHolder.getAsyncCommittingSessionManager());
    //修改全局事务状态为begin(1)
    SessionHolder.getAsyncCommittingSessionManager().addGlobalSession(this);
    //修改全局事务状态为AsyncCommitting(8)
    this.changeStatus(GlobalStatus.AsyncCommitting);
}

2.2、服务端的异步处理点2(开启调度任务获取异步提交事务)

init方法是在Server的mian方法中调用的

public void init() {
    //开启一些调度任务,这些调度任务循环执行的,处理一些异步任务
    retryRollbacking.scheduleAtFixedRate(() -> {
        try {
            //处理回滚的记录,可以异步进行处理
            handleRetryRollbacking();
        } catch (Exception e) {
            LOGGER.info("Exception retry rollbacking ... ", e);
        }
    }, 0, ROLLBACKING_RETRY_PERIOD, TimeUnit.MILLISECONDS);

    retryCommitting.scheduleAtFixedRate(() -> {
        try {
            //处理重试提交的
            handleRetryCommitting();
        } catch (Exception e) {
            LOGGER.info("Exception retry committing ... ", e);
        }
    }, 0, COMMITTING_RETRY_PERIOD, TimeUnit.MILLISECONDS);

    asyncCommitting.scheduleAtFixedRate(() -> {
        try {
            //处理异步提交的 1s执行一次
            handleAsyncCommitting();
        } catch (Exception e) {
            LOGGER.info("Exception async committing ... ", e);
        }
    }, 0, ASYNC_COMMITTING_RETRY_PERIOD, TimeUnit.MILLISECONDS);

    timeoutCheck.scheduleAtFixedRate(() -> {
        try {
            timeoutCheck();
        } catch (Exception e) {
            LOGGER.info("Exception timeout checking ... ", e);
        }
    }, 0, TIMEOUT_RETRY_PERIOD, TimeUnit.MILLISECONDS);

    undoLogDelete.scheduleAtFixedRate(() -> {
        try {
            undoLogDelete();
        } catch (Exception e) {
            LOGGER.info("Exception undoLog deleting ... ", e);
        }
    }, UNDO_LOG_DELAY_DELETE_PERIOD, UNDO_LOG_DELETE_PERIOD, TimeUnit.MILLISECONDS);
}

handleAsyncCommitting

/**
 * Handle async committing.
 * 异步提交任务,可能这里为了性能考虑,为了减少一些rcp的同步调用
 * 所以这里采用的异步处理
 */
protected void handleAsyncCommitting() {
    //获取所有的全局事务信息和分支事务信息(一个全局事务可能绑定多个分支事务)
    Collection<GlobalSession> asyncCommittingSessions = SessionHolder.getAsyncCommittingSessionManager()
        .allSessions();
    if (CollectionUtils.isEmpty(asyncCommittingSessions)) {
        return;
    }
    for (GlobalSession asyncCommittingSession : asyncCommittingSessions) {
        try {
            // Instruction reordering in DefaultCore#asyncCommit may cause this situation
            //如果全局事务的状态不是AsyncCommitting不处理
            if (GlobalStatus.AsyncCommitting != asyncCommittingSession.getStatus()) {
                continue;
            }
            asyncCommittingSession.addSessionLifecycleListener(SessionHolder.getRootSessionManager());
            //处理事务的异步提交
            core.doGlobalCommit(asyncCommittingSession, true);
        } catch (TransactionException ex) {
            LOGGER.error("Failed to async committing [{}] {} {}", asyncCommittingSession.getXid(), ex.getCode(), ex.getMessage(), ex);
        }
    }
}

io.seata.server.coordinator.DefaultCore#doGlobalCommit

public boolean doGlobalCommit(GlobalSession globalSession, boolean retrying) throws TransactionException {
    boolean success = true;
    // start committing event
    eventBus.post(new GlobalTransactionEvent(globalSession.getTransactionId(), GlobalTransactionEvent.ROLE_TC,
        globalSession.getTransactionName(), globalSession.getBeginTime(), null, globalSession.getStatus()));

    if (globalSession.isSaga()) {
        success = getCore(BranchType.SAGA).doGlobalCommit(globalSession, retrying);
    } else {
        //循环所有的分支事务的session
        for (BranchSession branchSession : globalSession.getSortedBranches()) {
            // if not retrying, skip the canBeCommittedAsync branches
            //判断是否能够异步提交
            if (!retrying && branchSession.canBeCommittedAsync()) {
                continue;
            }

            BranchStatus currentStatus = branchSession.getStatus();
            if (currentStatus == BranchStatus.PhaseOne_Failed) {
                globalSession.removeBranch(branchSession);
                continue;
            }
            try {
                //调用远程进行事务的提交,其实这里的远程就是调用的客户端的netty服务,告诉客户端可以删除业务表undo log日志,完成了事务的提交
                BranchStatus branchStatus = getCore(branchSession.getBranchType()).branchCommit(globalSession, branchSession);

                switch (branchStatus) {
                    case PhaseTwo_Committed:
                        //删除成移除本地分支事务branch_table
                        globalSession.removeBranch(branchSession);
                        continue;
                    case PhaseTwo_CommitFailed_Unretryable:
                        //远程删除失败则报错,如果不是异步提交,修改状态CommitFailed
                        if (globalSession.canBeCommittedAsync()) {
                            LOGGER.error(
                                "Committing branch transaction[{}], status: PhaseTwo_CommitFailed_Unretryable, please check the business log.", branchSession.getBranchId());
                            continue;
                        } else {
                           // 修改分支事务状态CommitFailed
                            SessionHelper.endCommitFailed(globalSession);
                            LOGGER.error("Committing global transaction[{}] finally failed, caused by branch transaction[{}] commit failed.", globalSession.getXid(), branchSession.getBranchId());
                            return false;
                        }
                    default:
                        if (!retrying) {
                            globalSession.queueToRetryCommit();
                            return false;
                        }
                        if (globalSession.canBeCommittedAsync()) {
                            LOGGER.error("Committing branch transaction[{}], status:{} and will retry later",
                                branchSession.getBranchId(), branchStatus);
                            continue;
                        } else {
                            LOGGER.error(
                                "Committing global transaction[{}] failed, caused by branch transaction[{}] commit failed, will retry later.", globalSession.getXid(), branchSession.getBranchId());
                            return false;
                        }
                }
            } catch (Exception ex) {
                StackTraceLogger.error(LOGGER, ex, "Committing branch transaction exception: {}",
                    new String[] {branchSession.toString()});
                if (!retrying) {
                    globalSession.queueToRetryCommit();
                    throw new TransactionException(ex);
                }
            }
        }
        if (globalSession.hasBranch()) {
            LOGGER.info("Committing global transaction is NOT done, xid = {}.", globalSession.getXid());
            return false;
        }
    }
    if (success && globalSession.getBranchSessions().isEmpty()) {
        //删除全局事务global_table
        SessionHelper.endCommitted(globalSession);

        // committed event
        eventBus.post(new GlobalTransactionEvent(globalSession.getTransactionId(), GlobalTransactionEvent.ROLE_TC,
            globalSession.getTransactionName(), globalSession.getBeginTime(), System.currentTimeMillis(),
            globalSession.getStatus()));

        LOGGER.info("Committing global transaction is successfully done, xid = {}.", globalSession.getXid());
    }
    return success;
}

3、客户端的处理

服务的getCore(branchSession.getBranchType()).branchCommit就调用到客户了,所以这里就要取看客户端的AbstractRMHandler处理了

3.1、客户端的同步处理

io.seata.rm.AbstractRMHandler#doBranchCommit

/**
 * Do branch commit.
 *接受TC发过来的异步提交请求
 * @param request  the request
 * @param response the response
 * @throws TransactionException the transaction exception
 */
protected void doBranchCommit(BranchCommitRequest request, BranchCommitResponse response)
    throws TransactionException {
    String xid = request.getXid();
    long branchId = request.getBranchId();
    String resourceId = request.getResourceId();
    String applicationData = request.getApplicationData();
    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("Branch committing: " + xid + " " + branchId + " " + resourceId + " " + applicationData);
    }
    /**
     * 这里其实调用了AsyncWorker的一个队列,将异步提交的任务放入到了一个队列中
     * 然后AsyncWorker有一个线程一直监听到这个队列(ASYNC_COMMIT_BUFFER),所以这里放入队列,AsyncWorker中的线程一直取这个队列中的数据
     * 取到就开始处理提交,就是删除undo log日志的内容
     */
    BranchStatus status = getResourceManager().branchCommit(request.getBranchType(), xid, branchId, resourceId,
        applicationData);
    response.setXid(xid);
    response.setBranchId(branchId);
    response.setBranchStatus(status);
    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("Branch commit result: " + status);
    }

}

客户端doBranchCommit其实就是将TC端发过来的分支事务提交(其实就是一个简单的删除undo log日志,因为事务完成了要删除这个log,所以seata这里采用的是异步来处理的,免得影响性能)
getResourceManager().branchCommit的调用线路为:

io.seata.rm.DefaultResourceManager#branchCommit
》io.seata.rm.datasource.DataSourceManager#branchCommit
》》io.seata.rm.datasource.AsyncWorker#branchCommit

public BranchStatus branchCommit(BranchType branchType, String xid, long branchId, String resourceId,
                                 String applicationData) throws TransactionException {
    //将异步提交的对象放入到队列ASYNC_COMMIT_BUFFER中,init中的有一个调度线程一直在对ASYNC_COMMIT_BUFFER取提交的数据,当取到数据过后
    //进行任务的执行(undo log日志的删除)
    if (!ASYNC_COMMIT_BUFFER.offer(new Phase2Context(branchType, xid, branchId, resourceId, applicationData))) {
        LOGGER.warn("Async commit buffer is FULL. Rejected branch [{}/{}] will be handled by housekeeping later.", branchId, xid);
    }
    return BranchStatus.PhaseTwo_Committed;
}

3.2、客户端的异步处理

客户端的异步处理和服务端的处理模式很像,就是用了一个异步调度线程去处理,上面的同步已经看了,TC端发过来的事务提交数据放入到了队列ASYNC_COMMIT_BUFFER中,所以客户端的异步线程的调度任务也是1s执行一次,执行的时候就从ASYNC_COMMIT_BUFFER中获取事务对象,当获取到了就开始处理,当然处理就比较简单了,处理的就是删除undo log日志。
io.seata.rm.datasource.AsyncWorker#init

/**
 * Init.
 */
public synchronized void init() {
    LOGGER.info("Async Commit Buffer Limit: {}", ASYNC_COMMIT_BUFFER_LIMIT);
    ScheduledExecutorService timerExecutor = new ScheduledThreadPoolExecutor(1, new NamedThreadFactory("AsyncWorker", 1, true));
    //启动一个schedule调度任务处理分支事务的提交
    timerExecutor.scheduleAtFixedRate(() -> {
        try {

            doBranchCommits();

        } catch (Throwable e) {
            LOGGER.info("Failed at async committing ... {}", e.getMessage());

        }
    }, 10, 1000 * 1, TimeUnit.MILLISECONDS);
}

io.seata.rm.datasource.AsyncWorker#doBranchCommits

private void doBranchCommits() {
    if (ASYNC_COMMIT_BUFFER.isEmpty()) {
        return;
    }

    Map<String, List<Phase2Context>> mappedContexts = new HashMap<>(DEFAULT_RESOURCE_SIZE);
    List<Phase2Context> contextsGroupedByResourceId;
    while (!ASYNC_COMMIT_BUFFER.isEmpty()) {
        //从队列中取出要提交的分支事务包装对象
        Phase2Context commitContext = ASYNC_COMMIT_BUFFER.poll();
        //从分支事务提交的包装对象中取出所有的resourceIds
        contextsGroupedByResourceId = CollectionUtils.computeIfAbsent(mappedContexts, commitContext.resourceId, key -> new ArrayList<>());
        contextsGroupedByResourceId.add(commitContext);
    }

    for (Map.Entry<String, List<Phase2Context>> entry : mappedContexts.entrySet()) {
        Connection conn = null;
        DataSourceProxy dataSourceProxy;
        try {
            try {
                DataSourceManager resourceManager = (DataSourceManager) DefaultResourceManager.get()
                    .getResourceManager(BranchType.AT);
                dataSourceProxy = resourceManager.get(entry.getKey());
                if (dataSourceProxy == null) {
                    throw new ShouldNeverHappenException("Failed to find resource on " + entry.getKey());
                }
                conn = dataSourceProxy.getPlainConnection();
            } catch (SQLException sqle) {
                LOGGER.warn("Failed to get connection for async committing on " + entry.getKey(), sqle);
                continue;
            }
            contextsGroupedByResourceId = entry.getValue();
            Set<String> xids = new LinkedHashSet<>(UNDOLOG_DELETE_LIMIT_SIZE);
            Set<Long> branchIds = new LinkedHashSet<>(UNDOLOG_DELETE_LIMIT_SIZE);
            //循环删除undo log日志内容
            for (Phase2Context commitContext : contextsGroupedByResourceId) {
                xids.add(commitContext.xid);
                branchIds.add(commitContext.branchId);
                int maxSize = Math.max(xids.size(), branchIds.size());
                /**
                 * 这里是批量删除,批量删除默认的大小是UNDOLOG_DELETE_LIMIT_SIZE=1000
                 * 每次等branchIds和xids满了1000过后进行删除,否则都只是将xid和bid放入集合中
                 * 每当集合满了1000就批量删除
                 */
                if (maxSize == UNDOLOG_DELETE_LIMIT_SIZE) {
                    try {
                        //删除undo 日志的内容,通过spi(io.seata.rm.datasource.undo.UndoLogManager)
                        //找到当前数据库是那种数据,比如mysql,然后调用batchDeleteUndoLog批量删除
                        UndoLogManagerFactory.getUndoLogManager(dataSourceProxy.getDbType()).batchDeleteUndoLog(
                            xids, branchIds, conn);
                    } catch (Exception ex) {
                        LOGGER.warn("Failed to batch delete undo log [" + branchIds + "/" + xids + "]", ex);
                    }
                    xids.clear();
                    branchIds.clear();
                }
            }

            //如果集合为空,表示在循环中已经全部删除了
            if (CollectionUtils.isEmpty(xids) || CollectionUtils.isEmpty(branchIds)) {
                return;
            }

            try {
                //这里删除xids和branchids中剩余没有删除的undo log日志
                UndoLogManagerFactory.getUndoLogManager(dataSourceProxy.getDbType()).batchDeleteUndoLog(xids,
                    branchIds, conn);
            } catch (Exception ex) {
                LOGGER.warn("Failed to batch delete undo log [" + branchIds + "/" + xids + "]", ex);
            }

            if (!conn.getAutoCommit()) {
                conn.commit();
            }
        } catch (Throwable e) {
            LOGGER.error(e.getMessage(), e);
            try {
                if (conn != null) {
                    conn.rollback();
                }
            } catch (SQLException rollbackEx) {
                LOGGER.warn("Failed to rollback JDBC resource while deleting undo_log ", rollbackEx);
            }
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException closeEx) {
                    LOGGER.warn("Failed to close JDBC resource while deleting undo_log ", closeEx);
                }
            }
        }
    }
}

三、seata工作原理

在这里插入图片描述

四、seata源码结构图

在这里插入图片描述

seata源码-全局事务回滚服务端源码 对于分布式事务,进行全局回滚的逻辑,还是比较简单的在事务管理者这边发起全局事务回滚的请求seata服务端,也就是事务协调者接收到请求之后,会向所有的rm,发起netty请求,进行分支事务的处理各个分支事务,会根据undoLog日志,生成回滚的sql,然后执行seata服务端在等分支事务返回状态之后,会先删除分支事务,在删除分支事务之前,会将分支事务加的锁给删除(这里的锁,如果是mysql的话,其实就是写入到mysql中的一条记录) 阅读详情

相关推荐

io.seata.core.exception.RmTransactionException: RPC Timeout

使用 seata 进行微服务分布式事务管理。

weixin_42579084的博客 2851

蚂蚁集团境外站点 Seata 实践与探索

文|李乔(花名:南桥)、李宗杰(花名:白鹰)李乔:蚂蚁集团高级开发工程师负责蚂蚁境外银行支付结算系统开发李宗杰:蚂蚁集团技术专家负责蚂蚁分布式事务中间件研发本文11580字 阅读 25分钟PART. 1背景蚂蚁国际境外银行业务正在部分迁移至阿里云,原内部使用的 SOFA 技术栈无法在阿里云上得到支持。为了满足银行业务快速发展、简化银行系统技术栈的目标,我们采用了...

金融级分布式架构 646

【微服务】(十六)—— 分布式事务Seata

目录 事务ACID原则 一、理论基础 1)CAP理论 CAP定理- Consistency CAP定理- Availability CAP定理-Partition tolerance 2)BASE理论 二、分布式事务Seata 1)初识seata 2)Seata架构 3)微服务集成seata 1、首先,引入seata相关依赖: 2、然后,配置application.yml,让微服务通过注册中心找到seata-tc-server: 三、XA模式 1)XA模式原理 2...

jizhibing的博客 2万+

seata在XA和AT模式下发生错误的问题解决

seata分布式事务在使用XA和AT发生的问题及解决方案

asdsa555656的博客 977

源码解析Seata AT模式中分支事务的提交或回滚是如何被触发的

在之前的博客中,已经介绍过了TM在seata AT模式中的处理流程、TC在seata分布式事务中的主要任务以及RM在seata AT模式中的sql语句执行流程,下面我们通过源码讲述分布式事务是如何实现提交或回滚的。

Java_zhujia的博客 1586

一文打通Seata源码的任督二脉

一、环境准备 1.源码下载 官方地址:https://seata.io/zh-cn/blog/download.html 通过idea打开seata-1.4.2版本的源码 2.回顾AT模式   其实在之前的应用课程中,我们已经用过AT模式,同时也写过一个小的Demo,那么这里其实我们主要要分析的是AT模式官方文档中的一些内容   官方文档:https://seata.io/zh-cn/docs/dev/mode/at-mode.html 2.1写隔离 一阶段本地事务提交前,需要确保先拿到全局锁 。 .

波波烤鸭的博客 2511

分布式事务:Seata框架AT模式及TCC模式执行流程剖析

Seata角色术语 TC - 事务协调者 维护全局和分支事务的状态,驱动全局事务提交或回滚,即Seata服务端。 TM - 事务管理器 定义全局事务的范围:开始全局事务、提交或回滚全局事务,在事务发起的客户端。 RM - 资源管理器 管理分支事务处理的资源,与TC交谈以注册分支事务和报告分支事务的状态,并驱动分支事务提交或回滚,在分支事务执行的客户端。 Seata执行流程 Seata...

朝雨忆轻尘 3110

零基础也能懂的Arduino ESP32离线安装包图文教程

手把手教你完成Arduino ESP32离线安装包的配置,无需联网也能快速搭建开发环境,适合初学者和网络受限用户,轻松实现arduino esp32离线安装包部署。

weixin_36213081的博客 2702

seata 如何开启tcc事物_分布式事务:Seata框架AT模式及TCC模式执行流程剖析

Seata角色术语TC - 事务协调者维护全局和分支事务的状态,驱动全局事务提交或回滚,即Seata服务端。TM - 事务管理器定义全局事务的范围:开始全局事务、提交或回滚全局事务,在事务发起的客户端。RM - 资源管理器管理分支事务处理的资源,与TC交谈以注册分支事务和报告分支事务的状态,并驱动分支事务提交或回滚,在分支事务执行的客户端。Seata执行流程Seata AT模式流程图解第一阶段通过...

weixin_39708502的博客 441

Windows 11 24H2 系统下,保姆级安装华为 eNSP 模拟器(含依赖软件下载与避坑指南)

本文提供Windows 11 24H2系统下华为eNSP模拟器的完整安装指南,涵盖系统配置调整、依赖软件安装及常见问题解决方案。特别针对新版系统的兼容性问题,提供详细的避坑步骤和优化建议,帮助网络工程师顺利完成eNSP模拟器的部署与使用。

weixin_42567752的博客 433

如何获取SAP BTP账户及BAS启用

返回到 Service Marketplace 点击SAP Business Application Studio 然后go to Application。进入子用户的OverView里面找到Entitlements添加SAP Business Application Studio。注意:在选购BTP免费环境的时候,使用人要选公司才可以成功。在完成上述操作后,就可以登陆Cockpit。这里有SAP官方的BTP试用的手顺链接。配置权限※我绑定的是登录时的邮箱。※过程中有问题可以在评论区讨论。

wangshulong2013的博客 726

Seata事务处理流程(主AT)

文章目录Seata事务处理流程前言一、组件装配二、核心组件源码分析1、GlobalTransactionScanner1.1、职能详解1.1.1、AbstractAutoProxyCreatorpostProcessBeforeInitializationwrapIfNecessary1.1.2、InitializingBean2、GlobalTransactionalInterceptor2.1、职能详解2.1.1、ConfigurationChangeListener2.1.2、MethodInterc

FantasyZsp的专栏 540

从数据到图片:手把手构建FMCW雷达人体行为识别数据集(行走、跌倒、喝水等6类动作)

本文详细解析了如何利用FMCW雷达构建人体行为识别数据集,涵盖行走、跌倒、喝水等6类动作。通过多普勒特征可视化、图像标准化处理和自动化流水线设计,将原始雷达信号转化为高质量时频图像数据集,为智能家居和健康监护等应用提供可靠数据支持。

weixin_30706691的博客 391

Seata AT模式的一些常见问题及其源码解析

1、异常时的全局事务处理流程;2、全局事务隔离级别;3、全局事务读已提交;

grant167的专栏 1096

开关电源环路学习笔记(1)-为啥要知道传递函数?

做硬件都会接触到开关电源,或多或少会接触到环路补偿。很多兄弟们也提出来让我说说这个,说明大家也都很关心,也说明这个好像有点难。 就我个人而言,我也想搞明白环路这一块,也查了一些资料,视频,不过说实话,一直都还是懵的,感觉很困难。 具体感觉就是,看资料或视频的时候,感觉好像是那么回事。但是撇开之后,就又云里雾里的感觉,总有一些想法没有找到答案。 问题 比如下面我想过的问题: 开关电源有开关,根本就不是一个线性系统,传递函数是咋弄出来的? 系统环路框图的输入量为什么不是Vin,而是参考电压V

weixin_42005993的博客 1万+

TGAT Python:图神经网络中的动态图算法

其中,图神经网络中的动态图算法成为了研究的热点之一。在模型的 forward 方法中,通过循环调用 TGATLayer 实例来进行图神经网络的前向传播。最终,模型返回图中节点的表示向量 output,可以用于图分类等任务。TGAT 算法的核心思想是在节点之间建立注意力连接,以捕捉节点在不同时间步之间的关系。TGAT 算法通过引入注意力机制和时间信息,从而有效地对动态图数据进行建模和分析。通过以上 Python 代码,我们可以方便地构建和训练 TGAT 模型,并在图分类任务中应用它。

2301_79366435的博客 1833

seata

seata应用 https://blog.csdn.net/weixin_46120888/article/details/123626096 分布式事务Seata的AT模式下两阶段提交原理 https://blog.csdn.net/qq_45076180/article/details/116795591 seata tcc理论实践 https://blog.csdn.net/huaishu/article/details/89880971 seata简单源码视频讲解 https://www.bilib

qq_36364521的博客 280

YOLOv8改进 | 主干网络 | 将主干网络替换为轻量化的ShuffleNetv2【原理 + 完整代码】

yolov8,yolov8创新,yolov8改进

kay_545 2569

分布式事务 Seata 教程 - AT模式源码分析之开启全局事务

在 AT 模式下,Seata 通过代理 JDBC 驱动的方式,在不修改原有应用程序代码的基础上,实现对本地事务的增强。Seata 将一个事务分为两阶段:全局提交阶段和全局回滚阶段。: 事务协调者,负责全局事务的管理。: 事务管理者,负责开始、提交或回滚全局事务。: 资源管理者,负责分支注册、状态汇报以及分支的提交与回滚。以上是对 Seata AT 模式的简要介绍和源码分析。实际开发中还需要关注异常处理、配置文件的设置等方面的内容。对于深入理解 Seata 的工作原理,阅读其官方文档和源码是非常必要的。

qq_33240556的博客 691

【AIGC】Qwen3-Embedding:Embedding与Rerank模型新标杆

Qwen3-Embedding:文本嵌入与重排序模型的技术解析与应用实践

一个内容严谨、方向前沿、极具实践价值的AI大模型技术分享站 3108

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

Seata原理

1 Seata架构 Seata目前支持四种分布式方案,其整体架构有很多相似之处,这里从整体上介绍方案,具体每种方案见相关博客。 1.1 整体架构 注:此图来自seata官网 TC (Transaction Coordinator) 事务协调者:维护全局和分支事务的状态,驱动全局事务提交或回滚。 TM (Transaction Manager)事务管理器:定义全局事务的范围:开始全局事务、提交或回滚全局事务。 RM (Resource Manager) 资源管理器:管理分支事务处理的资源,与TC交谈以注册

wuzhengfei1112的博客 841

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

[图文] Seata AT 模式分布式事务源码分析

推荐阅读 Seata TCC 分布式事务源码分析 公众号 Young_Blog 什么是 Seata AT 模式 Seata AT 的使用方法 第一步,增加全局事务注解 第二步,配置代理数据源 第三步,新建 undo_log 表 Seata AT 的工作流程 工作流程总览 图解 AT 模式一阶段流程 图解二阶段 Commit 流程 图解二阶段 Rollback 流程 本节小结 ...

旧时光 | YoungChen's 博客 3311

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

lwip-2.0.3

lwip是瑞典计算机科学院(SICS)的Adam Dunkels 开发的一个小型开源的TCP/IP协议栈。实现的重点是在保持TCP协议主要功能的基础上减少对RAM 的占用。

Seata源码分析 全局事务开启&提交&回滚流程

Seata源码版本为1.7.0源码下载路径一阶段这是分支事务主要的执行流程,不在本章节的源码分析范围内业务数据和志记录在同回滚日一个本地事务中提交,释放本地锁和连接资源。核心在于对业务sql进行解析,转换成undolog,并同时入库二阶段分布式事务操作成功,则TC通知RM异步删除undolog分布式事务操作失败,TM向TC发送回滚请求,RM 收到协调器TC发来的回滚请求,通过 XID 和 Branch ID 找到相应的回滚日志记录,通过回滚记录生成反向的更新 SQL 并执行,以完成分支的回滚。Seata生命

qq_44027353的博客 1674

Seata实战-AT模式分布式事务原理、源码分析

文章目录前言第一阶段第二阶段源码分析入口之Seata集成SpringTmClient.init()RmClient.init()第一阶段拦截器中开启事务业务逻辑执行与sql解析第二阶段 前言 上回文章里简单介绍了分布式事务相关概念,并测试跑通了Seata中AT模式Demo和TCC模式Demo,对Seata不了解的可以先看下 https://blog.csdn.net/hosaos/article...

hosaos的博客 1万+

分布式事务Seata的AT模式下两阶段提交原理

文章目录1. 扫描@GlobalTransactional注解,开启全局事务           Seata的AT模式的核心是对业务无侵入,是一种改进后的两阶段提交,其设计思路如下: 第一阶段:RM端提交本地事务,生成undo日志表,释放本地锁和连接资源。并向TC注册分支事务,通过全局事务的 XID 进行关联。 第二阶段:完全异步 分布式事务操作成功,则TC通知RM异步删除undo日志表 分布式事务操作失败,则TM

qq_1149513559的博客 4611

seata事务【回滚】原理及源码分析

Seata数据回滚原理及源码分析背景前言场景演示回顾 背景 Seata在年初开源,一经发布,社区活跃度一路走高,为赶上这一波潮流,于是乎自己也开始了seata的研究之路,具体的demo例子可以参考官网 和很多网友一样,本地的demo启动后各种问题随之出现,比如说启动找不到file.conf,代码异常后数据却不回滚等等,因为seata开源时间并不久,所以遇到问题也只能靠自己去调试查看源码去解决 前言...

flyfhj的博客 1万+
上一篇: seata源码分析(AT)-分支事务注册
下一篇: K8S部署rocketmq单机和集群
Life  journey
博客等级 码龄17年 1万+粉丝 80原创
评论 8
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址