一.概述
我们这个ccm-mall工程,核心接口就是下订单接口,在之前的章节已经讲解过,该接口涉及了四个微服务server-user、server-goods、server-pay和server-order.本章节我们将该接口加入seata分布式事务,保证在异常情况下的数据一致性.
二.server-user、server-goods、server-pay和server-order集成seata.
1.server-user、server-goods、server-pay和server-order的pom中加入相关依赖.
<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.2.0</version>
</dependency>
2.server-user、server-goods、server-pay和server-order的bootstrap.yml中加入相关配置.
seata:
enabled: true
application-id: ${
spring.application.name}
tx-service-group: my_test_tx_group
enable-auto-data-source-proxy: true
config:
type: nacos
nacos:
namespace:
serverAddr: 47.96.131.185:8849
group: SEATA_GROUP
userName: "nacos"
password: "nacos"
registry:
type: nacos
nacos:
application: seata-server #seata服务端(TC)在nacos中的应用名称
server-addr: 47.96.131.185:8849
namespace:
userName: "nacos"
password: "nacos"
3.user、pay、goods和order数据库加入表undo_log.
undo_log表sql脚本的位置:seata资源包路径:seata-1.2.0/script/client/at/db/mysql.sql
三.代码改造
1.下订单核心接口加入@GlobalTransactional注解,代表开启seata分布式事务管理
package com.ccm.server.order.service.impl;
import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.ccm.common.exception.CustomerException;
import com.ccm.common.exception.result.ResultSet;
import com.ccm.server.order.config.OrderIdGenerator;
import com.ccm.server.order.controller.req.PayOrderReq;
import com.ccm.server.order.dao.mysql.domain.OrderInfo;
import com.ccm.server.order.dao.mysql.domain.OrderSku;
import com.ccm.server.order.dao.mysql.mapper.OrderInfoMapper;
import com.ccm.server.order.dao.mysql.mapper.OrderSkuMapper;
import com.ccm.server.order.feign.ServerGoodsFeign;
import com.ccm.server.order.feign