Seata 是一款开源的分布式事务解决方案,致力于提供高性能和简单易用的分布式事务服务。Seata 将为用户提供了 AT、TCC、SAGA 和 XA 事务模式,为用户打造一站式的分布式解决方案。Seata官网
1.找到适合的Seata版本
参考:SpringCloudAlibaba SpringCloud SpringBoot 版本对照
依赖版本:
spring-boot:2.3.12.RELEASE
spring-cloud-alibaba:2.2.7.RELEASE
spring-cloud:Hoxton.SR12
nacos:2.0.3
seata: 1.3.0
2.下载合适版本的Seata源码下载
Release v1.3.0 · seata/seata · GitHub
wget https://github.com/seata/seata/archive/refs/tags/v1.3.0.zip
wget https://github.com/seata/seata/archive/refs/tags/v1.3.0.tar.gz3.配置启动Seata
3.1 初始化数据库
3.1.1 创建seata数据库
3.1.2 初始化表
资源链接:https://github.com/seata/seata/blob/1.3.0/script/server/db/mysql.sql
-- -------------------------------- The script used when storeMode is 'db' --------------------------------
-- the table to store GlobalSession data
CREATE TABLE IF NOT EXISTS `global_table`
(
    `xid`                       VARCHAR(128) NOT NULL,
    `transaction_id`            BIGINT,
    `status`                    TINYINT      NOT NULL,
    `application_id`            VARCHAR(32),
    `transaction_service_group` VARCHAR(32),
    `transaction_name`          VARCHAR(128),
    `timeout`                   INT,
    `begin_time`                BIGINT,
    `application_data`          VARCHAR(2000),
    `gmt_create`                DATETIME,
    `gmt_modified`              DATETIME,
    PRIMARY KEY (`xid`),
    KEY `idx_gmt_modified_status` (`gmt_modified`, `status`),
    KEY `idx_transaction_id` (`transaction_id`)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8;
-- the table to store BranchSession data
CREATE TABLE IF NOT EXISTS `branch_table`
(
    `branch_id`         BIGINT       NOT NULL,
    `xid`               VARCHAR(128) NOT NULL,
    `transaction_id`    BIGINT,
    `resource_group_id` VARCHAR(32),
    `resource_id`       VARCHAR(256),
    `branch_type`       VARCHAR(8),
    `status`            TINYINT,
    `client_id`         VARCHAR(64),
    `application_data`  VARCHAR(2000),
    `gmt_create`        DATETIME(6),
    `gmt_modified`      DATETIME(6),
    PRIMARY KEY (`branch_id`),
    KEY `idx_xid` (`xid`)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8;
-- the table to store lock data
CREATE TABLE IF NOT EXISTS `lock_table`
(
    `row_key`        VARCHAR(128) NOT NULL,
    `xid`            VARCHAR(96),
    `transaction_id` BIGINT,
    `branch_id`      BIGINT       NOT NULL,
    `resource_id`    VARCHAR(256),
    `table_name`     VARCHAR(32),
    `pk`             VARCHAR(36),
    `gmt_create`     DATETIME,
    `gmt_modified`   DATETIME,
    PRIMARY KEY (`row_key`),
    KEY `idx_branch_id` (`branch_id`)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8;3.2 完善Nacos相关配置
安装配置启动Nacos参考:Linux Nacos 快速启动_nacos linux快速启动-CSDN博客
3.2.1 新建命名空间 seata


3.2.2 修改config.txt
/seata/script/config-center/config.txt
service.vgroupMapping.my_test_tx_group=SEATA_GROUP
store.mode=db
store.db.url=jdbc:mysql://xxxx:3306/seata?useUnicode=true
store.db.user=seata
store.db.password=xxxx3.2.3 将配置信息推送至nacos
源码目录下:/seata-1.3.0/script/config-center/nacos/nacos-config.sh
chmod +x nacos-config.sh
./nacos-config.sh -h 127.0.0.1 -p 8848 -g SEATA_GROUP -t 61311143-2318-4af4-9180-ebbc0fxxxxx -u nacos -w nacos-h: host, 默认值 localhost
-p: port, 默认值 8848
-g: 配置分组 默认值 SEATA_GROUP
-t: 命名空间
-u: 用户名, nacos 1.2.0+ 之后添加权限验证 默认为''
-w: 密码, nacos 1.2.0+ 之后添加权限验证 默认为''
4. 配置启动Seata服务
wget https://github.com/seata/seata/releases/download/v1.3.0/seata-server-1.3.0.tar.gz
 wget https://github.com/seata/seata/releases/download/v1.3.0/seata-server-1.3.0.zip
4.1 修改registry.conf
服务目录下:/seata/conf/registry.conf
注意:命名空间需要与上文中生成的保持一致。
registry {
  # file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
  type = "nacos"
  nacos {
    application = "seata-server"
    serverAddr = "127.0.0.1:8848"
    group = "SEATA_GROUP"
    namespace = "61311143-2318-4af4-9180-ebxxx"
    username = "nacos"
    password = "nacos"
  }
}
config {
  # file、nacos 、apollo、zk、consul、etcd3、springCloudConfig
  type = "nacos"
  nacos {
    serverAddr = "127.0.0.1:8848"
    namespace = "61311143-2318-4af4-9180-ebxxx"
    group = "SEATA_GROUP"
    username = "nacos"
    password = "nacos"
  }
}
4.2 修改file.conf
服务目录下:/seata/conf/file.conf
## transaction log store, only used in seata-server
store {
  ## store mode: file、db、redis
  mode = "db"
  db {
    ## the implement of javax.sql.DataSource, such as DruidDataSource(druid)/BasicDataSource(dbcp)/HikariDataSource(hikari) etc.
    datasource = "druid"
    ## mysql/oracle/postgresql/h2/oceanbase etc.
    dbType = "mysql"
    driverClassName = "com.mysql.jdbc.Driver"
    url = "jdbc:mysql://Xx:3306/seata"
    user = "seata"
    password = "Xx"
    minConn = 5
    maxConn = 30
    globalTable = "global_table"
    branchTable = "branch_table"
    lockTable = "lock_table"
    queryLimit = 100
    maxWait = 5000
  }
}
4.3 启动服务
sh ./bin/seata-server.sh -h 127.0.0.1 -p 8091 -m db
-h nacos 地址
-p seata服务端口 默认8091
-m 存在事务日志的类型 file 文件 db 数据库 redis...

注意:将合适的数据库链接jar包放到 lib目录,(msyql8+ 使用seata/bin/jdbc/mysql-connector-java-8.0.19.jar)。
5.简单XA模式集成
5.1 业务库中添加表
参照官网:快速启动 | Seata
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 NOT NULL,
                             `log_modified` datetime NOT NULL,
                             `ext` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
                             PRIMARY KEY (`id`) USING BTREE,
                             UNIQUE INDEX `ux_undo_log`(`xid`, `branch_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = DYNAMIC;
5.2 添加依赖
此版本需要收到手动重新导入依赖包(1.3.0),否则jar冲突导致启动报错。
       <!-- seata -->
        <!-- https://mvnrepository.com/artifact/com.alibaba.cloud/spring-cloud-alibaba-seata -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-seata</artifactId>
            <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.3.0</version>
        </dependency>5.3 添加配置
my_test_tx_group使用需要注意。
seata:
  data-source-proxy-mode: XA # 开启XA事务
  registry: # TC服务注册中心的配置,微服务根据这些信息去注册中心获取tc服务地址
    # 参考tc服务自己的registry.conf中的配置
    type: nacos
    nacos: # tc
      server-addr: nacosip
      namespace: "命名空间ID"
      group: SEATA_GROUP
      application: seata-server # tc服务在nacos中的服务名称
      cluster: default #集群
  tx-service-group: my_test_tx_group # 事务组,根据这个获取tc服务的cluster名称
  service:
    grouplist:
      seata-server: 指定seata的IP端口
      vgroup-mapping: # 事务组与TC服务cluster的映射关系
        my_test_tx_group: default
5.4 测试表
参照官网:快速启动 | Seata
DROP TABLE IF EXISTS `order_tbl`;
CREATE TABLE `order_tbl` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` varchar(255) DEFAULT NULL,
`commodity_code` varchar(255) DEFAULT NULL,
`count` int(11) DEFAULT 0,
`money` int(11) DEFAULT 0,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `account_tbl`;
CREATE TABLE `account_tbl` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` varchar(255) DEFAULT NULL,
`money` int(11) DEFAULT 0,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
5.4测试代码
5.4.1订单
@RestController
@RequestMapping("/orderTbl")
public class OrderTblController {
    @Resource
    private OrderTblService orderTblService;
    @PostMapping("/add/{userId}/{money}")
    public CxResult<Boolean> add(@PathVariable("userId") String userId, @PathVariable("money") Integer money) {
        return CxResult.success(orderTblService.add(userId, money));
    }
}
public interface OrderTblService extends IService<OrderTbl> {
    Boolean add(String userId, Integer money);
}
@Service
public class OrderTblServiceImpl extends ServiceImpl<OrderTblMapper, OrderTbl> implements OrderTblService {
    @DubboReference
    private AccountProviderService accountProviderService;
    @Override
    @GlobalTransactional
    public Boolean add(String userId, Integer money) {
        OrderTbl orderTbl = new OrderTbl();
        orderTbl.setUserId(userId);
        orderTbl.setMoney(money);
        this.save(orderTbl);
        accountProviderService.addRecord(userId, money);
        if (money > 10000) {
            throw new BusinessException(ErrorMsg.COMMON_ERROR_1);
        }
        return Boolean.TRUE;
    }
}
5.4.2 账户
public interface AccountProviderService {
    void addRecord(String userId, Integer money);
}
@DubboService
public class AccountProvider implements AccountProviderService {
    @Resource
    private AccountTblService accountTblService;
    @Override
    @GlobalTransactional
    public void addRecord(String userId, Integer money) {
        AccountTbl accountTbl = new AccountTbl();
        accountTbl.setUserId(userId);
        accountTbl.setMoney(money);
        accountTblService.save(accountTbl);
    }
}


















