spring cloud 集成Seata 快速入门

时间:2021-04-13 16:32:24   收藏:0   阅读:97

Spring Cloud 快速集成 Seata

1. 添加依赖

添加Spring Cloud Alibaba 依赖管理工具和 Seata 依赖

GradleMaven

需要注意的是Spring Cloud Alibaba 的毕业版本的 GroupId 是 com.alibaba.cloud

spring-cloud-starter-alibaba-seata这个依赖中只依赖了spring-cloud-alibaba-seata,所以在项目中添加spring-cloud-starter-alibaba-seataspring-cloud-alibaba-seata是一样的

2. 添加Seata 配置文件

registry.conf

该配置用于指定 TC 的注册中心和配置文件,默认都是 file; 如果使用其他的注册中心,要求 Seata-Server 也注册到该配置中心上

registry.conf

file.conf

该配置用于指定TC的相关属性;如果使用注册中心也可以将配置添加到配置中心

file.conf

需要注意的是 service.vgroup_mapping这个配置,在 Spring Cloud 中默认是${spring.application.name}-fescar-service-group,可以通过指定application.properties的 spring.cloud.alibaba.seata.tx-service-group这个属性覆盖,但是必须要和 file.conf 中的一致,否则会提示 no available server to connect

3. 注入数据源

Seata 通过代理数据源的方式实现分支事务;MyBatis 和 JPA 都需要注入 io.seata.rm.datasource.DataSourceProxy, 不同的是,MyBatis 还需要额外注入 org.apache.ibatis.session.SqlSessionFactory

MyBatisJPA

如果使用的是 Hikari 数据源,需要修改数据源的配置,以及注入的 Bean 的配置前缀

spring.datasource.hikari.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.hikari.jdbc-url=jdbc:mysql://localhost:3306/seata?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true&useSSL=false
spring.datasource.hikari.username=root
spring.datasource.hikari.password=123456
@Bean
@ConfigurationProperties(prefix = "spring.datasource.hikari")
public DataSource dataSource() {
    return new HikariDataSource();
}

4. 添加 undo_log 表

在业务相关的数据库中添加 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

5. 启动 Seata-Server

在 https://github.com/seata/seata/releases 下载相应版本的 Seata-Server,修改 registry.conf为相应的配置(如果使用 file 则不需要修改),解压并通过以下命令启动:

sh ./bin/seata-server.sh

6. 使用@GlobalTransactional开启分布事务(2pc模式)

使用Transactional开启本地事务(最终消息表 通过mq传递消息)

在业务的发起方的方法上使用@GlobalTransactional开启全局事务,Seata 会将事务的 xid 通过拦截器添加到调用其他服务的请求中,实现分布式事务

原文:https://www.cnblogs.com/chenTo/p/14652551.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!