Seata 分布式事务 - Springboot 集成方案

Seata 分布式事务 - Springboot 集成方案

1.AT 模式 + Feign

1.1 初始化数据库

  • 每个库中的[undo_log]表,是 Seata AT 模式必须创建的表,主要用于分支事务的回滚。
-- ----------------------------
-- Table structure for undo_log
-- ----------------------------
DROP TABLE IF EXISTS `undo_log`;
CREATE TABLE `undo_log`  (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `branch_id` bigint(20) NOT NULL,
  `xid` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `context` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `rollback_info` longblob NOT NULL,
  `log_status` int(11) NOT NULL,
  `log_created` datetime(0) NOT NULL,
  `log_modified` datetime(0) NOT NULL,
  PRIMARY KEY (`id`) USING BTREE,
  UNIQUE INDEX `ux_undo_log`(`xid`, `branch_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

2.2 pom引入

<dependencies>
    <!-- Seata server 版本为 1.1.0  Seata client 也应为 1.1.0 -->
    <!-- 引入 Spring Cloud Alibaba Seata 相关依赖,使用 Seata 1.1.0 实现分布式事务,并实现对其的自动配置 -->
    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-seata</artifactId>
        <version>2021.1</version>
        <exclusions>
            <exclusion>
                <groupId>io.seata</groupId>
                <artifactId>seata-spring-boot-starter</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>io.seata</groupId>
        <artifactId>seata-spring-boot-starter</artifactId>
        <version>1.1.0</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-loadbalancer</artifactId>
        <version>3.0.5</version>
    </dependency>
    <!-- end 引入 Spring Cloud Alibaba Seata 相关依赖,使用 Seata 1.1.0 实现分布式事务,并实现对其的自动配置 -->
</dependencies>

2.3 配置文件

# Seata 配置项,对应 SeataProperties 类  spring.cloud.alibaba.seata
seata:
  # Seata 应用编号,默认为 ${spring.application.name}
  application-id: ${spring.application.name}
  # Seata 事务组编号,用于 TC 集群名
  tx-service-group: ${spring.application.name}-group
  # Seata 服务配置项,对应 ServiceProperties 类
  service:
    # 虚拟组和分组的映射
    vgroup-mapping:
      # ${spring.application.name}-group : default
      energytrading-cloud-app-order-group: default
  # Seata 注册中心配置项,对应 RegistryProperties 类
  registry:
    # 注册中心类型,默认为 file
    type: nacos 
    nacos:
      # 使用的 Seata 分组
      # cluster: DEFAULT_GROUP 
      # Nacos seata 命名空间
      namespace: seata
      # Nacos 服务地址
      serverAddr: 10.0.0.159 

2.4 注解使用

public class Seata{
    @GlobalTransactional(rollbackFor = Exception.class)
    public void seata(){
    }
}

3 参考文章

本文由 在码圈 创作,如果您觉得本文不错,请随意赞赏
采用 知识共享署名4.0 国际许可协议进行许可
您可以自由的转载和修改,但请务必注明文章来源并且不可用于商业目的。
本站部分内容收集于互联网,如果有侵权内容、不妥之处,请联系我们删除。敬请谅解!
原文链接:https://www.bedebug.com/archives/seata-3
最后更新于:2022-05-29 09:54:31

请博主喝咖啡 ☕.