Java开发中分布式事务解决方案Seata部署与使用(二)对接使用

1 业务服务添加依赖

<dependencies>
  <dependency>
    <groupId>io.seata</groupId>
    <artifactId>seata-spring-boot-starter</artifactId>
    <version>1.5.2</version>
  </dependency>
  <dependency>
    <groupId>io.seata</groupId>
    <artifactId>seata-all</artifactId>
    <version>1.5.2</version>
  </dependency>
  <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>
      <exclusion>
        <groupId>io.seata</groupId>
        <artifactId>seata-all</artifactId>
      </exclusion>
    </exclusions>
  </dependency>
</dependencies>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

3 业务服务配置增加以下内容

在单个业务服务的bootstrap.yml文件中,添加SpringBoot与Seata整合的相关配置,具体配置见当前文件夹中的client/seata-config.txt

APP_NAME 你的服务名称(唯一)
NACOS_IP:NACOS_PORT Nacos连接地址

seata:
  enabled: true
  application-id: APP_NAME
  tx-service-group: default_tx_group
  registry:
    type: nacos
    nacos:
      # seata 服务名,与前面配置的seata服务名称一致
      application: seata-server 
      # nacos ip地址
      server-addr: http://NACOS_IP:NACOS_PORT
      group: SEATA_GROUP
  config:
    type: nacos
    nacos:
      # nacos ip地址
      server-addr: http://NACOS_IP:NACOS_PORT
      group: SEATA_GROUP
      data-id: "seataServer.properties"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

4 发起事务端

在所需要进行远程服务调用操作的相关接口上(发起端)加上@GlobalTransactional(rollbackFor=Exception.class)注解

5 事务处理依赖表

在所需要事务处理的模块中创建undo_log数据表(每个服务都需要添加),数据库脚本如下(包括发起端和被调用端)

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for undo_log
-- ----------------------------
DROP TABLE IF EXISTS `undo_log`;
CREATE TABLE `undo_log`  (
  `branch_id` bigint(0) NOT NULL COMMENT 'branch transaction id',
  `xid` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT 'global transaction id',
  `context` varchar(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT 'undo_log context,such as serialization',
  `rollback_info` longblob NOT NULL COMMENT 'rollback info',
  `log_status` int(0) NOT NULL COMMENT '0:normal status,1:defense status',
  `log_created` datetime(6) NOT NULL COMMENT 'create datetime',
  `log_modified` datetime(6) NOT NULL COMMENT 'modify datetime',
  UNIQUE INDEX `ux_undo_log`(`xid`, `branch_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = 'AT transaction mode undo table' ROW_FORMAT = Dynamic;

SET FOREIGN_KEY_CHECKS = 1;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19