Fescar - RM 提交本地事务流程

简介: 开篇  这篇文章的目的是介绍Fescar的提交流程(Commit)和回滚流程(Rollback),这两个流程其实是Fescar中RM的核心逻辑,涉及和TC交互的流程。  由于RM和TC交互涉及到网络通信,所以这块我们暂时只关注RM端的处理流程而暂时忽略网络通信的过程,网络通信的过程值得通过一篇文章单独进行描述。

开篇

 这篇文章的目的是介绍Fescar的提交流程(Commit)和回滚流程(Rollback),这两个流程其实是Fescar中RM的核心逻辑,涉及和TC交互的流程。

 由于RM和TC交互涉及到网络通信,所以这块我们暂时只关注RM端的处理流程而暂时忽略网络通信的过程,网络通信的过程值得通过一篇文章单独进行描述。


RM提交事务源码分析

RM提交事务流程

public class ConnectionProxy extends AbstractConnectionProxy {

    public void commit() throws SQLException {

        // 如果是在全局事务当中的流程
        if (context.inGlobalTransaction()) {
            try {
                // 1、注册全局事务
                register();
            } catch (TransactionException e) {
                recognizeLockKeyConflictException(e);
            }

            try {
                if (context.hasUndoLog()) {
                    // 2、持久化回滚日志
                    UndoLogManager.flushUndoLogs(this);
                }
                // 3、提交本地事务
                targetConnection.commit();
            } catch (Throwable ex) {
                report(false);
                if (ex instanceof SQLException) {
                    throw (SQLException) ex;
                } else {
                    throw new SQLException(ex);
                }
            }
            // 4、上报状态
            report(true);
            context.reset();

        } else {
            // 如果不在全局事务当中的流程
            targetConnection.commit();
        }
    }
}

说明:

  • RM的提交事务区分为在全局事务和不在全局事务两种场景。
  • RM的提交事务不在全局事务的场景是直接通过数据库连接targetConnection.commit()提交事务。
  • RM的提交事务在全局事务的场景中则按照:1、注册事务;2、持久化回滚日志;3、提交本地事务;4、上报状态。
  • 注册事务register()。
  • 持久化回滚日志UndoLogManager.flushUndoLogs(this)。
  • 提交本地事务 targetConnection.commit()。
  • 上报状态 report(true)。


RM 分支事务注册

public class ConnectionProxy extends AbstractConnectionProxy {

    private void register() throws TransactionException {
        Long branchId = DataSourceManager.get().branchRegister(BranchType.AT, getDataSourceProxy().getResourceId(),
                null, context.getXid(), context.buildLockKeys());
        context.setBranchId(branchId);
    }
}


public class ConnectionContext {
    public String buildLockKeys() {
        if (lockKeysBuffer.isEmpty()) {
            return null;
        }
        StringBuffer appender = new StringBuffer();
        Iterator<String> iterable = lockKeysBuffer.iterator();
        while (iterable.hasNext()) {
            appender.append(iterable.next());
            if (iterable.hasNext()) {
                appender.append(";");
            }
        }
        return appender.toString();
    }
}


public class DataSourceManager implements ResourceManager {

    private ResourceManagerInbound asyncWorker;
    private Map<String, Resource> dataSourceCache = new ConcurrentHashMap<>();

    public void setAsyncWorker(ResourceManagerInbound asyncWorker) {
        this.asyncWorker = asyncWorker;
    }

    @Override
    public Long branchRegister(BranchType branchType, String resourceId, String clientId, 
                               String xid, String lockKeys) throws TransactionException {
        try {
            BranchRegisterRequest request = new BranchRegisterRequest();
            request.setTransactionId(XID.getTransactionId(xid));
            request.setLockKey(lockKeys);
            request.setResourceId(resourceId);
            request.setBranchType(branchType);

            BranchRegisterResponse response = (BranchRegisterResponse) 
                        RmRpcClient.getInstance().sendMsgWithResponse(request);
            if (response.getResultCode() == ResultCode.Failed) {
                throw new TransactionException(response.getTransactionExceptionCode(), 
                       "Response[" + response.getMsg() + "]");
            }
            return response.getBranchId();
        } catch (TimeoutException toe) {
            throw new TransactionException(TransactionExceptionCode.IO, "RPC Timeout", toe);
        } catch (RuntimeException rex) {
            throw new TransactionException(TransactionExceptionCode.BranchRegisterFailed,
                          "Runtime", rex);
        }
    }
}

说明:

  • 分支事务的注册过程是通过DataSourceManager的branchRegister()实现的。
  • branchRegister的内部逻辑先组装BranchRegisterRequest并发送给TC。
  • branchRegister的内部逻辑后接收TC的响应BranchRegisterResponse并返回执行结果。
  • 核心的lockKeys的拼接逻辑是拼接所有lockKeysBuffer的内容,lockKeysBuffer是所有受影响行拼接的字符串,相当于整合二次索引的感觉


RM 持久化回滚日志

public final class UndoLogManager {

    private static final Logger LOGGER = LoggerFactory.getLogger(UndoLogManager.class);

    private static String UNDO_LOG_TABLE_NAME = "undo_log";

    private static String INSERT_UNDO_LOG_SQL = "INSERT INTO " + UNDO_LOG_TABLE_NAME + "\n" +
        "\t(branch_id, xid, rollback_info, log_status, log_created, log_modified)\n" +
        "VALUES (?, ?, ?, 0, now(), now())";
    private static String DELETE_UNDO_LOG_SQL = "DELETE FROM " + UNDO_LOG_TABLE_NAME + "\n" +
        "\tWHERE branch_id = ? AND xid = ?";

    private static String SELECT_UNDO_LOG_SQL = "SELECT * FROM " 
       + UNDO_LOG_TABLE_NAME + " WHERE log_status = 0 AND branch_id = ? AND xid = ? FOR UPDATE";

    private UndoLogManager() {

    }

    public static void flushUndoLogs(ConnectionProxy cp) throws SQLException {
        assertDbSupport(cp.getDbType());

        ConnectionContext connectionContext = cp.getContext();
        String xid = connectionContext.getXid();
        long branchID = connectionContext.getBranchId();
        // 组装分支回滚日志对象
        BranchUndoLog branchUndoLog = new BranchUndoLog();
        branchUndoLog.setXid(xid);
        branchUndoLog.setBranchId(branchID);
        branchUndoLog.setSqlUndoLogs(connectionContext.getUndoItems());
        // 序列化回滚日志对象
        String undoLogContent = UndoLogParserFactory.getInstance().encode(branchUndoLog);

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Flushing UNDO LOG: " + undoLogContent);
        }
        
        // 保存数据库回滚日志对象
        PreparedStatement pst = null;
        try {
            pst = cp.getTargetConnection().prepareStatement(INSERT_UNDO_LOG_SQL);
            pst.setLong(1, branchID);
            pst.setString(2, xid);
            pst.setBlob(3, BlobUtils.string2blob(undoLogContent));
            pst.executeUpdate();
        } catch (Exception e) {
            if (e instanceof SQLException) {
                throw (SQLException) e;
            } else {
                throw new SQLException(e);
            }
        } finally {
            if (pst != null) {
                pst.close();
            }
        }

    }
}

说明:

  • 构建回滚日志的逻辑核心在于组装数据结果序列化后保存到数据表当中。
  • 组装分支回滚日志对象。
  • 序列化回滚日志对象。
  • 保存数据库回滚日志对象。


RM分支事务状态汇报

public class ConnectionProxy extends AbstractConnectionProxy {

    private void report(boolean commitDone) throws SQLException {
        int retry = 5; // TODO: configure
        while (retry > 0) {
            try {
                DataSourceManager.get().branchReport(context.getXid(), context.getBranchId(),
                        (commitDone ? BranchStatus.PhaseOne_Done : BranchStatus.PhaseOne_Failed), null);
                return;
            } catch (Throwable ex) {
                LOGGER.error("Failed to report [" + context.getBranchId() + 
                         "/" + context.getXid() + "] commit done [" + 
                        commitDone + "] Retry Countdown: " + retry);
                retry--;

                if (retry == 0) {
                    throw new SQLException("Failed to report branch status " + commitDone, ex);
                }
            }
        }
    }
}

public class DataSourceManager implements ResourceManager {

    public void branchReport(String xid, long branchId, BranchStatus status, String applicationData)
            throws TransactionException {
        try {
            BranchReportRequest request = new BranchReportRequest();
            request.setTransactionId(XID.getTransactionId(xid));
            request.setBranchId(branchId);
            request.setStatus(status);
            request.setApplicationData(applicationData);

            BranchReportResponse response = (BranchReportResponse) 
                      RmRpcClient.getInstance().sendMsgWithResponse(request);
            if (response.getResultCode() == ResultCode.Failed) {
                throw new TransactionException(response.getTransactionExceptionCode(), 
                        "Response[" + response.getMsg() + "]");
            }
        } catch (TimeoutException toe) {
            throw new TransactionException(TransactionExceptionCode.IO, "RPC Timeout", toe);
        } catch (RuntimeException rex) {
            throw new TransactionException(TransactionExceptionCode.BranchReportFailed, "Runtime", rex);
        }

    }

说明:

  • 分支事务的report过程是通过DataSourceManager的branchReport()实现的。
  • branchReport的内部逻辑先组装BranchReportRequest并发送给TC。
  • branchReport的内部逻辑后接收TC的响应BranchReportResponse并返回执行结果。


期待

 下一篇文章会尝试分析RM回滚事务流程。


Fescar源码分析连载

Fescar 源码解析系列

相关实践学习
【涂鸦即艺术】基于云应用开发平台CAP部署AI实时生图绘板
【涂鸦即艺术】基于云应用开发平台CAP部署AI实时生图绘板
目录
相关文章
|
JavaScript
若依框架-------弹层表格
若依框架-------弹层表格
1139 0
|
对象存储 开发者
对象OSS生命周期(LifeCycle)管理功能|学习笔记
快速学习对象 OSS 生命周期(LifeCycle)管理功能
3635 0
对象OSS生命周期(LifeCycle)管理功能|学习笔记
|
分布式计算 Java 大数据
Apache SeaTunnel 3 分钟入门指南
Apache SeaTunnel 3 分钟入门指南
1881 0
|
存储 关系型数据库 MySQL
DataX: 阿里开源的又一款高效数据同步工具
DataX 是由阿里巴巴集团开源的一款大数据同步工具,旨在解决不同数据存储之间的数据迁移、同步和实时交换的问题。它支持多种数据源和数据存储系统,包括关系型数据库、NoSQL 数据库、Hadoop 等。 DataX 提供了丰富的数据读写插件,可以轻松地将数据从一个数据源抽取出来,并将其加载到另一个数据存储中。它还提供了灵活的配置选项和高度可扩展的架构,以适应各种复杂的数据同步需求。
|
4月前
|
编译器 程序员 C语言
C语言深度解析:未定义行为(UB)—— 90%玄学bug的根源
C语言因极致性能与硬件控制力成为系统开发首选,但其“自由”伴生未定义行为(UB):语法合法却结果不可控,是“调试正常、上线崩溃”的元凶。UB包括数组越界、有符号溢出、空指针解引用、序列点违规、重复释放等,编译器可任意优化或崩溃。规避需严守边界、开启高警告、判空置空、拆分表达式、预检溢出。(239字)
IDEA Error:java: Compilation failed: internal java compiler error 解决办法
IDEA Error:java: Compilation failed: internal java compiler error 解决办法
1291 0
|
人工智能 IDE 开发工具
寻找Cursor的替代品:10款AI编程工具深度评测与推荐·优雅草卓伊凡
寻找Cursor的替代品:10款AI编程工具深度评测与推荐·优雅草卓伊凡
10506 18
寻找Cursor的替代品:10款AI编程工具深度评测与推荐·优雅草卓伊凡
|
12月前
|
固态存储 IDE 开发工具
电脑无法识别固态硬盘怎么办?
本文详解固态硬盘(SSD)无法被电脑识别的常见问题及解决方法。涵盖硬件连接、BIOS设置、系统识别、驱动安装等方面,适用于新手与老用户。分析四种常见识别失败情况,并提供排查步骤与解决方案,助你快速定位问题并修复。
课时20:集合的运算
本内容介绍集合的运算,涵盖交集、并集、差集、异或集及子集等概念。通过Python代码示例详细说明各运算符(如 &、|、-、^、&lt;=、&lt;、&gt;=、&gt;)的使用方法,并解释其在实际编程中的应用。重点在于理解集合运算的基本原理及其在编程中的实现,帮助读者掌握集合运算的基础知识。
|
数据采集 监控 物联网
IOT/智能设备日志解决方案(1):概述
无论是物联网还是智能设备,规模都越来越大,产业分工也越来越明确,逐渐形成一整套的生态系统。而同时无论是物联网还是智能设备的生态系统中,日志数据永远是不可缺少的一个重要环节。
6467 0
IOT/智能设备日志解决方案(1):概述