目录
Spring Boot单体项目集成Seata
(1)下载Seata服务器和源码的安装包
(2)建表(仅DB模式下需要建三张表)
(3)修改registry.conf的配置
(4)修改file.conf中的配置
如果使用DB模式,file.config需要修改两点
①修改存储模式:store.mode = “db”
②修改数据库连接
registry {
# file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
type = "file"
file {
name = "file.conf"
}
}
config {
# file、nacos 、apollo、zk、consul、etcd3、springCloudConfig
type = "file"
file {
name = "file.conf"
}
}
(5)启动Seata Server
启动方式 | 描述 |
---|---|
windows启动 | 点击 seata-server.bat |
linux启动 | 执行seata-server.sh |
源码启动 | 执行server模块下io.seata.server.Server.java的main方法 |
命令启动 | bin/seata-server.sh -h 127.0.0.1 -p 8091 -m db -n 1 -e test |
(6)Spring Boot项目配置
由于是Spring Boot单体项目,不同数据库的调用需要使用多数据源,在此基础上才能产生分布式事务。当出现业务异常时,需要undo_log表来进行事务回滚,所以每一个数据库都要建一个undo_log表
注意:
(1)undo_log表并不是mysql自带的undo_log日志版本链
(2)undo_log表是Seata的AT模式自带的表,用于数据回滚,AT模式不使用undo_log日志版本链进行回滚,
(3)原生的XA模式(不是seata的XA模式)的回滚就用的是mysql自带的undo_log日志版本链
# AT模式下的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,
PRIMARY KEY (`id`),
UNIQUE KEY `ux_undo_log` (`xid`,`branch_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
1.引入seata依赖
<!--seata对springboot的支持 -->
<dependency>
<groupId>io.seata</groupId>
<artifactId>seata-spring-boot-starter</artifactId>
<version>1.4.2</version>
</dependency>
2.指定seata事务分组,用于从TC获取seata server服务实例
由于TC是独立部署的,可能这个TC集群服务了很多项目,它内部通过group做了服务隔离, 所以需要配置一个group用于确定seata server的服务实例
#Seata事务分组
spring.cloud.alibaba.seata.tx-service-group=my_test_tx_group
3.配置全局事务@GlobalTransactional注解
Spring Boot项目下的分布式事务,需要切换多数据源,而使用seata保证全局事务,需要对每个数据源进行一次代理,通过代理往TC注册分支事务信息
另外Seata的AT模式依赖于本地事务,在下单 -> 减库存 -> 扣账户余额的过程中,每一个操作都需要加@Transtional注解,只需要在最外层加上@GlobalTransactional注解即可开启分布式事务,这也是seata对业务零侵入的体现
#分布式事务seata配置
seata:
# 默认关闭,如需启用spring.datasource.dynamic.seata需要同时开启
enabled: true
# Seata 应用编号,默认为 ${spring.application.name}
application-id: ${spring.application.name}
# Seata 事务组编号,用于 TC 集群名
tx-service-group: ${spring.application.name}-group
# 关闭自动代理
enable-auto-data-source-proxy: false
如果执行成功,如上所示,seata-server的日志如下