← 返回学习路线

SYSTEM

Seata 分布式事务

Java基础Seatasystem
src/content/notes/system/Seata.md

Seata

分布事物

一个分布式事务过程,可以用分布式处理过程的一 ID + 三组件模型来描述:

  • XID (Transaction ID):全局唯一的事务 ID,在这个事务ID下的所有事务会被统一控制

  • TC (Transaction Coordinator):事务协调者,维护全局和分支事务的状态,驱动全局事务提交或回滚

  • TM (Transaction Manager):事务管理器,定义全局事务的范围,开始全局事务、提交或回滚全局事务

  • RM (Resource Manager):资源管理器,管理分支事务处理的资源,与 TC 交谈以注册分支事务和报告分支事务的状态,并驱动分支事务提交或回滚

典型的分布式事务流程:

  1. TM 向 TC 申请开启一个全局事务,全局事务创建成功并生成一个全局唯一的 XID
  2. XID 在微服务调用链路的上下文中传播(也就是在多个 TM,RM 中传播)
  3. RM 向 TC 注册分支事务,将其纳入 XID 对应全局事务的管辖
  4. TM 向 TC 发起针对 XID 的全局提交或回滚决议
  5. TC 调度 XID 下管辖的全部分支事务完成提交或回滚请求
Cloud-分布式事务流程

基本配置

Seata 是一款开源的分布式事务解决方案,致力于提供高性能和简单易用的分布式事务服务。Seata 将为用户提供了 AT、TCC、SAGA 和 XA 事务模式,为用户打造一站式的分布式解决方案

下载 seata-server 文件修改 conf 目录下的配置文件

  • file.conf:自定义事务组名称、事务日志存储模式为 db、数据库连接信息

事务分组:seata 的资源逻辑,可以按微服务的需要,在应用程序(客户端)对自行定义事务分组,每组取一个名字

Cloud-Seata配置文件

启动 Nacos 和 Seata,如果 DB 报错,需要把将 lib 文件夹下 mysql-connector-java-5.1.30.jar 删除,替换为自己 MySQL 连接器版本

Cloud-Seata配置成功

官网:https://seata.io

下载地址:https://github.com/seata/seata/releases

基本介绍:https://seata.io/zh-cn/docs/overview/what-is-seata.html


基本使用

两个注解:

  • Spring 提供的本地事务:@Transactional

  • Seata 提供的全局事务:@GlobalTransactional

搭建简单 Demo:

  • 创建 UNDO_LOG 表:SEATA AT 模式需要 UNDO_LOG 表,如果一个模块的事务提交了,Seata 会把提交了哪些数据记录到 undo_log 表中,如果这时 TC 通知全局事务回滚,那么 RM 就从 undo_log 表中获取之前修改了哪些资源,并根据这个表回滚

    -- 注意此处0.3.0+ 增加唯一索引 ux_undo_log
    CREATE TABLE `undo_log` (
      `id` bigint(20) NOT NULL AUTO_INCREMENT,
      `branch_id` bigint(20) NOT NULL,
      `xid` varchar(100) NOT NULL,
      `context` varchar(128) NOT NULL,
      `rollback_info` longblob NOT NULL,
      `log_status` int(11) NOT NULL,
      `log_created` datetime NOT NULL,
      `log_modified` datetime NOT NULL,
      `ext` varchar(100) DEFAULT NULL,
      PRIMARY KEY (`id`),
      UNIQUE KEY `ux_undo_log` (`xid`,`branch_id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
  • 引入 pom 依赖:

    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-seata</artifactId>
        <version>${spring-cloud-alibaba.version}</version>
    </dependency>
  • application.yml:

    spring:
      application:
        name: seata-order-service
      cloud:
        alibaba:
          seata:
            # 自定义事务组名称需要与seata-server中file.conf中配置的事务组ID对应
            # vgroup_mapping.my_test_tx_group = "my_group"
            tx-service-group: my_group
        nacos:
          discovery:
            server-addr: localhost:8848
      datasource:
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://localhost:3306/seata_order?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC
        username: root
        password:[已隐藏]
  • 构建三个服务:

    // 仓储服务
    public interface StorageService {
        // 扣除存储数量
        void deduct(String commodityCode, int count);
    }
    
    // 订单服务
    public interface OrderService {
    	// 创建订单
        Order create(String userId, String commodityCode, int orderCount);
    }
    
    // 帐户服务
    public interface AccountService {
        // 从用户账户中借出
        void debit(String userId, int money);
    }
  • 业务逻辑:增加 @GlobalTransactional 注解

    public class OrderServiceImpl implements OrderService {
    	@Resource
        private OrderDAO orderDAO;
    	@Resource
        private AccountService accountService;
        
    	@Transactional(rollbackFor = Exception.class)
        public Order create(String userId, String commodityCode, int orderCount) {
            int orderMoney = calculate(commodityCode, orderCount);
    		// 账户扣钱
            accountService.debit(userId, orderMoney);
    
            Order order = new Order();
            order.userId = userId;
            order.commodityCode = commodityCode;
            order.count = orderCount;
            order.money = orderMoney;
    
            return orderDAO.insert(order);
        }
    }
    public class BusinessServiceImpl implements BusinessService {
    	@Resource
        private StorageService storageService;
    	@Resource
        private OrderService orderService;
    
        // 采购,涉及多服务的分布式事务问题
        @GlobalTransactional
        @Transactional(rollbackFor = Exception.class)
        public void purchase(String userId, String commodityCode, int orderCount) {
            storageService.deduct(commodityCode, orderCount);
            orderService.create(userId, commodityCode, orderCount);
        }
    }

详细示例参考:https://github.com/seata/seata-samples/tree/master/springcloud-nacos-seata