目录
- 1、添加依赖
- 2.、配置Seata
- 3、创建AT模式表
- 4、使用Seata分布式事务
1、添加依赖
<dependency><groupId>io.seata</groupId><artifactId>seata-spring-boot-starter</artifactId></dependency>
上述依赖适用于springboot项目
如果你的项目是springcloud项目,那么可以使用下面这个依赖
<dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-seata</artifactId></dependency>
spring-cloud-starter-alibaba-seata是为Spring Cloud应用程序开发的,可以在Spring Cloud环境中使用,并提供了与Spring Cloud Config、Eureka、Nacos等应用程序所需的集成。它依赖于Spring Cloud Alibaba项目,因此需要引入spring-cloud-starter-alibaba-dependencies的BOM(Bill of Materials),来管理版本依赖关系。
spring-cloud-starter-alibaba-seata推荐依赖配置方式,自定义seata-spring-boot-starter版本
<dependency><groupId>io.seata</groupId><artifactId>seata-spring-boot-starter</artifactId><version>最新版</version></dependency><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-seata</artifactId><version>最新版本</version><exclusions><exclusion><groupId>io.seata</groupId><artifactId>seata-spring-boot-starter</artifactId></exclusion></exclusions></dependency>
2.、配置Seata
在 Spring Boot 应用的配置文件(application.yml 或 application.properties)中配置 Seata 相关参数,例如:
application.yml
seata:enabled: trueapplication-id: your_application_idtx-service-group: default_tx_groupenable-auto-data-source-proxy: truedata-source-proxy-mode: ATservice:vgroup-mapping:default_tx_group: defaultregistry:type: nacosnacos:server-addr: 127.0.0.1:8848group: SEATA_GROUPnamespace:username: nacospassword: nacosconfig:type: nacosnacos:server-addr: 127.0.0.1:8848group: SEATA_GROUPdata-id: seataServer.propertiesnamespace:username: nacospassword: nacos
上面我seata的注册和配置都放到了nacos上,nacos上的配置可以看我上一篇文章:https://blog.csdn.net/qq_36551991/article/details/135968940
注:data-id要与我们nacos创建的配置文件的data-id一致,这里默认的data-id为seata.properties
对于多个服务来说,都需要配置seata,而且注册中心需要一致
3、创建AT模式表
在AT模式下,每个业务数据库都必须创建 undo_log 表,undo_log 表是 Seata AT模式必须创建的表,主要用于分支事务的回滚
表机构地址:https://github.com/apache/incubator-seata/tree/master/script/client/at/db
大家在上面地址选择自己使用的数据库的sql脚本,进行执行,我的数据库是mysql,所以使用的是mysql.sql
Mysql表结构如下:
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;
4、使用Seata分布式事务
在我们的事务方法上添加@GlobalTransactional注解即可开启全局事务,主服务加上@GlobalTransactional注解即可,被调用服务不用加@GlobalTransactional和@Transactional;
下面是一个示例样板:
//seata全局事务注解@GlobalTransactional (rollbackFor=Exception.class)public void createOrder(Integer userId, Integer productId) {log.info("当前 XID: {}", RootContext.getXID());//1、减库存productFeigne.reduceStock(productId, 1);//2、减余额accountFeign.reduceBalance(userId, product.getPrice());//3、下订单Orders order = new Orders();ordersMapper.insertSelective(order);}