一个调用链中的所有微服务都是seata的客户端,都必须走下面的步骤
第一步:创建undo_log表
下载地址:https://github.com/seata/seata/tree/develop/script/client/at/db
-- for AT mode you must to init this sql for you business database. the seata server not need it.
CREATE TABLE IF NOT EXISTS `undo_log`
(
`branch_id` BIGINT(20) NOT NULL COMMENT 'branch transaction id',
`xid` VARCHAR(100) NOT NULL COMMENT 'global transaction id',
`context` VARCHAR(128) NOT NULL COMMENT 'undo_log context,such as serialization',
`rollback_info` LONGBLOB NOT NULL COMMENT 'rollback info',
`log_status` INT(11) NOT NULL COMMENT '0:normal status,1:defense status',
`log_created` DATETIME(6) NOT NULL COMMENT 'create datetime',
`log_modified` DATETIME(6) NOT NULL COMMENT 'modify datetime',
UNIQUE KEY `ux_undo_log` (`xid`, `branch_id`)
) ENGINE = InnoDB
AUTO_INCREMENT = 1
DEFAULT CHARSET = utf8 COMMENT ='AT transaction mode undo table';
第二步:pom依赖
<!-- seata -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-seata</artifactId>
<version>2.2.0.RELEASE</version>
<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.4.2</version>
</dependency>
第三步:配置
seata:
enabled: true
tx-service-group: fengmi_tx_group
enable-auto-data-source-proxy: true
config:
type: nacos
nacos:
server-addr: 127.0.0.1:8848
group: DEFAULT_GROUP
namespace: sit
username: nacos
password: nacos
data-id: fengmi_tx_group-sit.properties
registry: #发现seata-server
type: nacos
nacos:
application: seata-server
server-addr: 127.0.0.1:8848
namespace: sit
group: DEFAULT_GROUP
username: nacos
password: nacos
第四步:@Globaltransational注解
示例:
一个项目,orders和goods两个微服务,goods和orders分别有自己的数据库
goods的service
goods的dao
goods的controller 运行之后在数据库的库存减1
orders的service,通过openfeign暴露接口在orders服务里面调用goods。
orders的dao 增加订单
orders的controller 减少库存并且增加一个订单
正常应该减少库存增加订单,但是有1/0的报错,这个时候通过@GlobalTransactional注解会回滚所以数据库不会发生变化。