Seata的三个基本概念:
TC (Transaction Coordinator) - 事务协调者
维护全局和分支事务的状态,驱动全局事务提交或回滚。
TM (Transaction Manager) - 事务管理器
定义全局事务的范围:开始全局事务、提交或回滚全局事务。
RM (Resource Manager) - 资源管理器
管理分支事务处理的资源,与TC交谈以注册分支事务和报告分支事务的状态,并驱动分支事务提交或回滚。
使用Seata
1.创建具有InnoDB引擎的MySQL数据库
2.创建 UNDO_LOG 表
- -- 注意此处0.3.0+ 增加唯一索引 ux_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;
3.从Releases · seata/seata · GitHub,下载服务器软件包,将其解压缩。
4.pom引入seata,同时注意版本是否和下载的版本对应上
-
-
com.alibaba.cloud -
spring-cloud-starter-alibaba-seata -

5.修改seata的conf文件(当使用nacos作为注册中心的时候):

只需修改前六行
- registry {
- # file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
- type = "nacos"
-
- nacos {
- # 你的nacos地址
- serverAddr = "localhost:8848"
6.启动seata

去nacos注册中心可以看到,seata已经注册进了nacos
7.对需要用到分布式事务的service方法上加上注解:
@GlobalTransactional
8.对于需要用到分布式事务的微服务都使用seata代理自己的数据源
- import com.zaxxer.hikari.HikariDataSource;
- import io.seata.rm.datasource.DataSourceProxy;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.util.StringUtils;
- import javax.sql.DataSource;
-
- @Configuration
- public class MySeataConfig {
-
- @Autowired
- DataSourceProperties dataSourceProperties;
-
- @Bean
- public DataSource dataSource(DataSourceProperties dataSourceProperties) {
- HikariDataSource dataSource = dataSourceProperties.initializeDataSourceBuilder().type(HikariDataSource.class).build();
- if (StringUtils.hasText(dataSourceProperties.getName())) {
- dataSource.setPoolName(dataSourceProperties.getName());
- }
- return new DataSourceProxy(dataSource);
- }
-
- }
9.将file.conf和registry.conf复制到用到seata的微服务的resource文件夹下

打开resouce中的file.conf,修改31行,将“my_test_tx_group”修改成自己的微服务名字+“-fescar-service-group”,比如:
vgroup_mapping.gulimall-order-fescar-service-group = "default"
注:对于主事务使用@GlobalTransactional,主事务调用的其它微服务的分支事务只需要用@Transactional即可