一、seata简介
1、seata的官网
首先,学习任何中间件我们先从官网看起,官网对各阶段模块都有详细的介绍,这里我们对seata做一个简单的介绍。
2、seata的各角色介绍
Seata 是一款开源的分布式事务解决方案,致力于提供高性能和简单易用的分布式事务服务。Seata 将为用户提供了 AT、TCC、SAGA 和 XA 事务模式,为用户打造一站式的分布式解决方案。这篇文章我们重点介绍AT模式的实现。
要了解Seata,首先我们要了解一下Seata的几个关键的概念:
- TC (Transaction Coordinator) - 事务协调者
维护全局和分支事务的状态,驱动全局事务提交或回滚。
- TM (Transaction Manager) - 事务管理器(发起者,同时也是RM的一种)
定义全局事务的范围:开始全局事务、提交或回滚全局事务。
- RM (Resource Manager) - 资源管理器(每个参与事务的微服务)
管理分支事务处理的资源,与TC交谈以注册分支事务和报告分支事务的状态,并驱动分支事务提交或回滚。
二、seata-server的下载和启动
1、seata-server的下载
使用seata处理分布式事务,我们必须下载seata-server作为TC的角色,来协调全局事务的处理,本文章使用的是1.5.2版本的seata-server,大家注意版本的选择,尽量和文章保持一致,不然可能会有和其他依赖版本不一致的问题。
官方下载地址:https://github.com/seata/seata/releases
进入下载页面选择v1.5.2版本,下载到本地
2、seata-server的配置文件修改
下载后解压到本地,进入\seata\conf\application.yml,修改文件中的配置项,主要配置seata的配置中心和注册中心的参数信息,具体配置参数如下
#seata的服务端口 server: port: 7091 #seata的应用服务名称 spring: application: name: seata-server #console的参数,必须配置,不配置的话启动参数解析会报错,我理解这是1.5.0版本的一个bug console: user: username: password: #seata的配置中心参数,这里选择的nacos的配置方式 seata: config: # support: nacos, consul, apollo, zk, etcd3 type: nacos nacos: server-addr: 127.0.0.1:8848 group: SEATA_GROUP namespace: seata username: nacos password: nacos data-id: seataServer.properties #seata的注册中心的配置参数,这里选择的是nacos的配置中心 registry: # support: nacos, eureka, redis, zk, consul, etcd3, sofa type: nacos nacos: application: seata-server server-addr: 127.0.0.1:8848 group: SEATA_GROUP namespace: cluster: default username: nacos password: nacos # server: # service-port: 8091 #If not configured, the default is '${server.port} + 1000' security: secretKey: SeataSecretKey0c382ef121d778043159209298fd40bf3850a017 tokenValidityInMilliseconds: 1800000 ignore: urls: /,/**/*.css,/**/*.js,/**/*.html,/**/*.map,/**/*.svg,/**/*.png,/**/*.ico,/console-fe/public/**,/api/v1/auth/login
3、application.yml中配置中心和注册中心参数详解
-
配置中心参数解释
seata:
config:
# support: nacos, consul, apollo, zk, etcd3
type: nacos #选择的配置中心类型为nacos
nacos:
server-addr: 127.0.0.1:8848 #配置中心的地址
group: SEATA_GROUP #配置中心的分组
namespace: seata #配置中心使用的命名空间
username: nacos
password: nacos
data-id: seataServer.properties#配置中心中的数据ID
-
注册中心参数解释
registry:
# support: nacos, eureka, redis, zk, consul, etcd3, sofa
type: nacos #注册中心类型
nacos:
application: seata-server #应用名称
server-addr: 127.0.0.1:8848 #注册中心地址
group: SEATA_GROUP #注册中心的分组名称
namespace: #注册中心的命名空间
cluster: default #注册中心的集群配置,和配置中心dataID下面
service.vgroupMapping.mygroup的参数保持一致
username: nacos
password: nacos
讲道理,配置完上面的这些参数seata-server的配置就完成了,可以启动,但是因为依赖nacos,所以需要把下面的nacos配置启动完成之后再启动seata-server.
三、nacos的下载和启动
1、nacos的官网地址
官网网址:https://nacos.io/zh-cn/index.html
Nacos = **注册中心+配置中心组合**
2、naocs的下载地址
这里下载的是nacos的2.1.0版本,搭配上面1.5.2版本的seata-server
3、启动nacos
下载之后解压到本地,进入\nacos-server-2.1.0\bin直接启动,如下图,在cmd模式下,输入指令
./startup.cmd -m standalone
启动成功之后访问地址localhost:8848/nacos,账号密码都是nacos,一下页面为正常启动后访问页面
四、nacos配置中心dataID配置
1、创建命名空间seata
根据步骤二seata-server中配置文件中配置中心的参数,在nacos的配置文件中创建命名空间seata
2、配置nacos配置参数
然后在配置列表的seata命名空间中创建第二步骤中的dataID为seataServer.properties的配置参数
3、seataServer.properties配置参数详解
transport.type=TCP
transport.server=NIO
transport.heartbeat=true
transport.enableTmClientBatchSendRequest=false
transport.enableRmClientBatchSendRequest=true
transport.enableTcServerBatchSendResponse=false
transport.rpcRmRequestTimeout=30000
transport.rpcTmRequestTimeout=30000
transport.rpcTcRequestTimeout=30000
transport.threadFactory.bossThreadPrefix=NettyBoss
transport.threadFactory.workerThreadPrefix=NettyServerNIOWorker
transport.threadFactory.serverExecutorThreadPrefix=NettyServerBizHandler
transport.threadFactory.shareBossWorker=false
transport.threadFactory.clientSelectorThreadPrefix=NettyClientSelector
transport.threadFactory.clientSelectorThreadSize=1
transport.threadFactory.clientWorkerThreadPrefix=NettyClientWorkerThread
transport.threadFactory.bossThreadSize=1
transport.threadFactory.workerThreadSize=default
transport.shutdown.wait=3
transport.serialization=seata
transport.compressor=none
#Transaction routing rules configuration, only for the client
service.vgroupMapping.mygroup=default
#If you use a registry, you can ignore it
service.default.grouplist=127.0.0.1:8091
service.enableDegrade=false
service.disableGlobalTransaction=false
#Transaction rule configuration, only for the client
client.rm.asyncCommitBufferLimit=10000
client.rm.lock.retryInterval=10
client.rm.lock.retryTimes=30
client.rm.lock.retryPolicyBranchRollbackOnConflict=true
client.rm.reportRetryCount=5
client.rm.tableMetaCheckEnable=true
client.rm.tableMetaCheckerInterval=60000
client.rm.sqlParserType=druid
client.rm.reportSuccessEnable=false
client.rm.sagaBranchRegisterEnable=false
client.rm.sagaJsonParser=fastjson
client.rm.tccActionInterceptorOrder=-2147482648
client.tm.commitRetryCount=5
client.tm.rollbackRetryCount=5
client.tm.defaultGlobalTransactionTimeout=60000
client.tm.degradeCheck=false
client.tm.degradeCheckAllowTimes=10
client.tm.degradeCheckPeriod=2000
client.tm.interceptorOrder=-2147482648
client.undo.dataValidation=true
client.undo.logSerialization=jackson
client.undo.onlyCareUpdateColumns=true
server.undo.logSaveDays=7
server.undo.logDeletePeriod=86400000
client.undo.logTable=undo_log
client.undo.compress.enable=true
client.undo.compress.type=zip
client.undo.compress.threshold=64k
#For TCC transaction mode
tcc.fence.logTableName=tcc_fence_log
tcc.fence.cleanPeriod=1h
#Log rule configuration, for client and server
log.exceptionRate=100
#Transaction storage configuration, only for the server. The file, DB, and redis configuration values are optional.
store.mode=db
store.lock.mode=db
store.session.mode=db
#Used for password encryption
#If `store.mode,store.lock.mode,store.session.mode` are not equal to `file`, you can remove the configuration block.
store.file.dir=file_store/data
store.file.maxBranchSessionSize=16384
store.file.maxGlobalSessionSize=512
store.file.fileWriteBufferCacheSize=16384
store.file.flushDiskMode=async
store.file.sessionReloadReadSize=100
#seata的数据表配置
store.db.datasource=druid
store.db.dbType=mysql
store.db.driverClassName=com.mysql.cj.jdbc.Driver
store.db.url=jdbc:mysql://127.0.0.1:3306/seata?useUnicode=true&rewriteBatchedStatements=true
store.db.user=root
store.db.password=root
store.db.minConn=5
store.db.maxConn=30
store.db.globalTable=global_table
store.db.branchTable=branch_table
store.db.distributedLockTable=distributed_lock
store.db.queryLimit=100
store.db.lockTable=lock_table
store.db.maxWait=5000
#These configurations are required if the `store mode` is `redis`. If `store.mode,store.lock.mode,store.session.mode` are not equal to `redis`, you can remove the configuration block.
store.redis.mode=single
store.redis.single.host=127.0.0.1
store.redis.single.port=6379
store.redis.maxConn=10
store.redis.minConn=1
store.redis.maxTotal=100
store.redis.database=0
store.redis.queryLimit=100
#Transaction rule configuration, only for the server
server.recovery.committingRetryPeriod=1000
server.recovery.asynCommittingRetryPeriod=1000
server.recovery.rollbackingRetryPeriod=1000
server.recovery.timeoutRetryPeriod=1000
server.maxCommitRetryTimeout=-1
server.maxRollbackRetryTimeout=-1
server.rollbackRetryTimeoutUnlockEnable=false
server.distributedLockExpireTime=10000
server.xaerNotaRetryTimeout=60000
server.session.branchAsyncQueueSize=5000
server.session.enableBranchAsyncRemove=false
server.enableParallelRequestHandle=false
#Metrics configuration, only for the server
metrics.enabled=false
metrics.registryType=compact
metrics.exporterList=prometheus
metrics.exporterPrometheusPort=9898
4、创建seata-server使用的数据表
seata-server做为TC事务协调者,在分布式事务的处理过程中,需要用到四个数据表global_table(全局事务记录表)、branch_table(分支事务记录表)、lock_table(全局锁表)、distributed_lock(分布式锁),具体的数据表脚本如下:
这几个表的数据库链接信息配置在上面seataServer.properties中,如下:
#seata的数据表配置
store.db.datasource=druid
store.db.dbType=mysql
store.db.driverClassName=com.mysql.cj.jdbc.Driver
store.db.url=jdbc:mysql://127.0.0.1:3306/seata?useUnicode=true&rewriteBatchedStatements=true
store.db.user=root
store.db.password=root
store.db.minConn=5
store.db.maxConn=30
store.db.globalTable=global_table
store.db.branchTable=branch_table
store.db.distributedLockTable=distributed_lock
store.db.queryLimit=100
store.db.lockTable=lock_table
store.db.maxWait=5000
-- -------------------------------- The script used when storeMode is 'db' --------------------------------
-- the table to store GlobalSession data
CREATE TABLE IF NOT EXISTS `global_table`
(
`xid` VARCHAR(128) NOT NULL,
`transaction_id` BIGINT,
`status` TINYINT NOT NULL,
`application_id` VARCHAR(32),
`transaction_service_group` VARCHAR(32),
`transaction_name` VARCHAR(128),
`timeout` INT,
`begin_time` BIGINT,
`application_data` VARCHAR(2000),
`gmt_create` DATETIME,
`gmt_modified` DATETIME,
PRIMARY KEY (`xid`),
KEY `idx_status_gmt_modified` (`status` , `gmt_modified`),
KEY `idx_transaction_id` (`transaction_id`)
) ENGINE = InnoDB
DEFAULT CHARSET = utf8mb4;
-- the table to store BranchSession data
CREATE TABLE IF NOT EXISTS `branch_table`
(
`branch_id` BIGINT NOT NULL,
`xid` VARCHAR(128) NOT NULL,
`transaction_id` BIGINT,
`resource_group_id` VARCHAR(32),
`resource_id` VARCHAR(256),
`branch_type` VARCHAR(8),
`status` TINYINT,
`client_id` VARCHAR(64),
`application_data` VARCHAR(2000),
`gmt_create` DATETIME,
`gmt_modified` DATETIME,
PRIMARY KEY (`branch_id`),
KEY `idx_xid` (`xid`)
) ENGINE = InnoDB
DEFAULT CHARSET = utf8mb4;
-- the table to store lock data
CREATE TABLE IF NOT EXISTS `lock_table`
(
`row_key` VARCHAR(128) NOT NULL,
`xid` VARCHAR(128),
`transaction_id` BIGINT,
`branch_id` BIGINT NOT NULL,
`resource_id` VARCHAR(256),
`table_name` VARCHAR(32),
`pk` VARCHAR(36),
`status` TINYINT NOT NULL DEFAULT '0' COMMENT '0:locked ,1:rollbacking',
`gmt_create` DATETIME,
`gmt_modified` DATETIME,
PRIMARY KEY (`row_key`),
KEY `idx_status` (`status`),
KEY `idx_branch_id` (`branch_id`),
KEY `idx_xid_and_branch_id` (`xid` , `branch_id`)
) ENGINE = InnoDB
DEFAULT CHARSET = utf8mb4;
CREATE TABLE IF NOT EXISTS `distributed_lock`
(
`lock_key` CHAR(20) NOT NULL,
`lock_value` VARCHAR(20) NOT NULL,
`expire` BIGINT,
primary key (`lock_key`)
) ENGINE = InnoDB
DEFAULT CHARSET = utf8mb4;
INSERT INTO `distributed_lock` (lock_key, lock_value, expire) VALUES ('AsyncCommitting', ' ', 0);
INSERT INTO `distributed_lock` (lock_key, lock_value, expire) VALUES ('RetryCommitting', ' ', 0);
INSERT INTO `distributed_lock` (lock_key, lock_value, expire) VALUES ('RetryRollbacking', ' ', 0);
INSERT INTO `distributed_lock` (lock_key, lock_value, expire) VALUES ('TxTimeoutCheck', ' ', 0);
五、seata-server的启动
以上涉及seata-server依赖nacos的注册中心启动和配置中心配置之后,就可以启动seata-server了,进入\seata\bin,直接点击seata-server.bat启动seata-server
seata启动完成之后,进入nacos观察服务列表,可以看到seata-server已经做为一个服务注册上来了
到这里,seata-server依赖nacos做为注册中心和配置中心的搭建已经完成,下面我们编写业务代码模块来验证seata实现分布式事务处理的能力。
六、分布式业务模块的搭建
1、业务场景
这里我们创建两个功能模块,订单模块seata-order和库存模块seata-stock,编写业务代码,让订单模块去调用库存模块,先减少库存,然后创建订单,如果订单创建失败,所有分支事务的数据都回滚。这里订单模块做为TM事务的管理者(发起者)、订单模块和库存模块具体的业务操作做为RM实现分支事务的注册和处理。(为了演示方便,这里只涉及订单和库存两个模块)
2、业务表结构
这里涉及两个功能模块,seata-order订单工程和seata-stock库存工程,这两个功能分别用独立的数据库test_order(order表和undo_log表)和 test_stock(stock表和undo_log表)
DROP TABLE IF EXISTS `order`;
CREATE TABLE `order` (
`product` varchar(255) NOT NULL,
`count` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for stock
-- ----------------------------
DROP TABLE IF EXISTS `stock`;
CREATE TABLE `stock` (
`product` varchar(255) DEFAULT NULL,
`count` int(11) DEFAULT NULL,
`money` int(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for undo_log
-- ----------------------------
DROP TABLE IF EXISTS `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 DEFAULT CHARSET=utf8;
3、搭建业务项目
-
主项目
主项目的pom依赖:注意这里spring-cloud-alibaba采用的版本是2.2.9-release
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.12.RELEASE</version>
<relativePath/>
</parent>
<groupId>com.czing</groupId>
<artifactId>springnacos</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springnacos</name>
<packaging>pom</packaging>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>2.2.7.RELEASE</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>2.2.9.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<modules>
<module>seata-order</module>
<module>seata-stock</module>
</modules>
</project>
-
seata-order模块的代码搭建
pom文件:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.czing</groupId>
<artifactId>springnacos</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.czing</groupId>
<artifactId>seata-order</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>seata-order</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>2.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-seata</artifactId>
</dependency>
<dependency>
<groupId>io.seata</groupId>
<artifactId>seata-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.5</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.yml的配置文件
server: port: 8888 spring: application: name: seata-order-8888 cloud: nacos: discovery: server-addr: localhost:8848 group: SEATA_GROUP datasource: type: com.alibaba.druid.pool.DruidDataSource druid: url: jdbc:mysql://localhost:3306/test_order?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai driver-class-name: com.mysql.cj.jdbc.Driver username: root password: root service-url: nacos-user-service: http://seata-stock-8777 seata: application-id: ${spring.application.name} # seata 服务分组,要与服务端seataServer.properties配置service.vgroup_mapping的后缀对应 tx-service-group: mygroup registry: # 指定nacos作为注册中心 type: nacos nacos: application: seata-server server-addr: 127.0.0.1:8848 namespace: group: SEATA_GROUP config: # 指定nacos作为配置中心 type: nacos nacos: server-addr: 127.0.0.1:8848 namespace: seata group: SEATA_GROUP data-id: seataServer.properties
代码结构截图和具体业务代码
config层下面的MybatisConfig类实现数据源的代理,重要!!!数据源只有被代理才能实现分支事务的注册和回滚,因为这个问题我排查了两天,诸位注意。
package com.czing.order.config;
import com.alibaba.druid.pool.DruidDataSource;
import io.seata.rm.datasource.DataSourceProxy;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import javax.sql.DataSource;
/**
*
* 需要用到分布式事务的微服务都需要使用seata DataSourceProxy代理自己的数据源
*/
@Configuration
@MapperScan("com.czing.order.mapper")
public class MybatisConfig {
/**
* 从配置文件获取属性构造datasource,注意前缀,这里用的是druid,根据自己情况配置,
* 原生datasource前缀取"spring.datasource"
*
* @return
*/
@Bean
@ConfigurationProperties(prefix = "spring.datasource.druid")
public DruidDataSource druidDataSource() {
DruidDataSource druidDataSource = new DruidDataSource();
return druidDataSource;
}
/**
* 构造datasource代理对象,替换原来的datasource
* @param druidDataSource
* @return
*/
@Primary
@Bean("dataSource")
public DataSource dataSourceProxy(DruidDataSource druidDataSource) {
// return new DataSourceProxyXA(druidDataSource);
return new DataSourceProxy(druidDataSource);
}
@Bean(name = "sqlSessionFactory")
public SqlSessionFactory sqlSessionFactoryBean(DataSource dataSource) throws Exception {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
//设置代理数据源
factoryBean.setDataSource(dataSource);
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
factoryBean.setMapperLocations(resolver.getResources("classpath*:mybatis/**/*-mapper.xml"));
org.apache.ibatis.session.Configuration configuration=new org.apache.ibatis.session.Configuration();
//使用jdbc的getGeneratedKeys获取数据库自增主键值
configuration.setUseGeneratedKeys(true);
//使用列别名替换列名
configuration.setUseColumnLabel(true);
//自动使用驼峰命名属性映射字段,如userId ---> user_id
configuration.setMapUnderscoreToCamelCase(true);
factoryBean.setConfiguration(configuration);
return factoryBean.getObject();
}
}
client层的StockClient类,为了通过restTemplate远程调用stock模块,这里也可以采用feign的方式调用
package com.czing.order.client;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
/**
* @Description TODO
* @Author wangchengzhi
* @Date 2023/9/24 21:43
*/
@Service
public class StockClient {
@Value("${service-url.nacos-user-service}")
private String serviceUrl;
@Autowired
private RestTemplate restTemplate;
public String decr(){
ResponseEntity<String> result = restTemplate.getForEntity(serviceUrl+"/stockInfo/decr",String.class);
return result.getBody();
}
}
controller入口层
package com.czing.order.controller;
import com.czing.order.client.StockClient;
import com.czing.order.service.OrderInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @Description TODO
* @Author wangchengzhi
* @Date 2023/9/24 15:06
*/
@RestController
@RequestMapping(value = "/orderInfo")
public class OrderInfo {
@Autowired
private StockClient stockClient;
@Autowired
private OrderInfoService orderInfoService;
/**
* @Author wangchengzhi
* @Description创建订单
* @Date 15:30 2023/9/24
* @Param
* @return
**/
@GetMapping(value = "/create")
public String create(){
//创建订单
String s = orderInfoService.creatOrder();
return s;
}
}
service层的接口和其实现类
package com.czing.order.service;
/**
* @Author wangchengzhi
* @Description 订单的相关操作
* @Date 15:28 2023/9/24
* @Param
* @return
**/
public interface OrderInfoService {
String creatOrder();
}
package com.czing.order.service.impl;
import com.czing.order.client.StockClient;
import com.czing.order.mapper.OrderMapper;
import com.czing.order.service.OrderInfoService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @Description TODO
* @Author wangchengzhi
* @Date 2023/9/24 15:14
*/
@Service
public class OrderInfoServiceImpl implements OrderInfoService {
@Autowired
private StockClient stockClient;
@Autowired
private OrderMapper orderMapper;
@GlobalTransactional
@Override
public String creatOrder() {
//减少库存
String decr = stockClient.decr();
int i = 1/0;
boolean order = orderMapper.createOrder();
if(order){
return "创建订单成功";
}else{
return "订单创建失败";
}
}
}
数据处理层mapper下面的OrderMapper
package com.czing.order.mapper;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Component;
@Component
@Mapper
public interface OrderMapper {
@Insert("INSERT INTO order (`product`, `count`) VALUES ('老北京','6')")
boolean createOrder();
}
order工程的启动类
package com.czing.order;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
@EnableDiscoveryClient
public class SeataOrderApplication {
public static void main(String[] args) {
SpringApplication.run(SeataOrderApplication.class, args);
}
@Bean
@LoadBalanced
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
-
seata-stock模块的代码搭建
pom文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.czing</groupId>
<artifactId>springnacos</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.czing</groupId>
<artifactId>seata-stock</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>seata-stock</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.5</version>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-seata</artifactId>
</dependency>
<dependency>
<groupId>io.seata</groupId>
<artifactId>seata-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
config下面的MybatisConfig实现数据源代理类
package com.czing.stock.config;
import com.alibaba.druid.pool.DruidDataSource;
import io.seata.rm.datasource.DataSourceProxy;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import javax.sql.DataSource;
/**
*
* 需要用到分布式事务的微服务都需要使用seata DataSourceProxy代理自己的数据源
*/
@Configuration
@MapperScan("com.czing.stock.mapper")
public class MybatisConfig {
/**
* 从配置文件获取属性构造datasource,注意前缀,这里用的是druid,根据自己情况配置,
* 原生datasource前缀取"spring.datasource"
*
* @return
*/
@Bean
@ConfigurationProperties(prefix = "spring.datasource.druid")
public DruidDataSource druidDataSource() {
DruidDataSource druidDataSource = new DruidDataSource();
return druidDataSource;
}
/**
* 构造datasource代理对象,替换原来的datasource
* @param druidDataSource
* @return
*/
@Primary
@Bean("dataSource")
public DataSource dataSourceProxy(DruidDataSource druidDataSource) {
// return new DataSourceProxyXA(druidDataSource);
return new DataSourceProxy(druidDataSource);
}
@Bean(name = "sqlSessionFactory")
public SqlSessionFactory sqlSessionFactoryBean(DataSource dataSource) throws Exception {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
//设置代理数据源
factoryBean.setDataSource(dataSource);
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
factoryBean.setMapperLocations(resolver.getResources("classpath*:mybatis/**/*-mapper.xml"));
org.apache.ibatis.session.Configuration configuration=new org.apache.ibatis.session.Configuration();
//使用jdbc的getGeneratedKeys获取数据库自增主键值
configuration.setUseGeneratedKeys(true);
//使用列别名替换列名
configuration.setUseColumnLabel(true);
//自动使用驼峰命名属性映射字段,如userId ---> user_id
configuration.setMapUnderscoreToCamelCase(true);
factoryBean.setConfiguration(configuration);
return factoryBean.getObject();
}
}
controller入口类
package com.czing.stock.controller;
import com.czing.stock.service.impl.StockInfoService;
import io.seata.core.context.RootContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @Description TODO
* @Author wangchengzhi
* @Date 2023/9/24 15:12
*/
@RestController
@RequestMapping(value = "/stockInfo")
public class StockController {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
StockInfoService stockInfoService;
@RequestMapping(value = "/decr")
public String decr(){
logger.info("当前 XID: {}", RootContext.getXID());
return stockInfoService.decr();
}
}
service层的接口和实现类
package com.czing.stock.service.impl;
/**
* @Author wangchengzhi
* @Description 库存相关的操作
* @Date 15:15 2023/9/24
* @Param
* @return
**/
public interface StockInfoService {
//减少库存
String decr();
}
package com.czing.stock.service.impl;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import com.czing.stock.mapper.StockMapper;
/**
* @Description 库存相关操作的实现类
* @Author wangchengzhi
* @Date 2023/9/24 15:14
*/
@Service
public class StockInfoServiceImpl implements StockInfoService {
@Resource
private StockMapper stockMapper;
@Override
public String decr() {
stockMapper.decr();
return "我是库存管理者,你进来啦";
}
}
mapper层的StockMapper类
package com.czing.stock.mapper;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Update;
@Mapper
public interface StockMapper {
@Update("update stock set count = count-1 where product='老北京' ")
boolean decr();
}
启动类
package com.czing.stock;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
@EnableDiscoveryClient
public class SeataStockApplication {
public static void main(String[] args) {
SpringApplication.run(SeataStockApplication.class, args);
}
}
七、分布式事务的异常回滚验证
1、启动seata-order和seata-stock项目
nacos的服务列表注册情况
2、调用seata-order的入口
调用地址:localhost:8888/orderInfo/create
seata-order创建订单的具体逻辑
@Service
public class OrderInfoServiceImpl implements OrderInfoService {
@Autowired
private StockClient stockClient;
@Autowired
private OrderMapper orderMapper;
@GlobalTransactional
@Override
public String creatOrder() {
//减少库存
String decr = stockClient.decr();
//为了让事务报错,验证数据回滚的场景
int i = 1/0;
//创建订单
boolean order = orderMapper.createOrder();
if(order){
return "创建订单成功";
}else{
return "订单创建失败";
}
}
}
启动之后seata的TM和RM注册成功的截图
3、事务注册回滚的流程
调用localhost:8888/orderInfo/create的时候增加@GlobalTransactional注解开启全局事务,调用进来的时候把全局事务的xid写入global_table表
执行String decr = stockClient.decr()减少库存之后,开启分支事务记录到branch_table表,并开启分支事务的表锁记录到lock_table表。
调用库存之后分支事务会存数据到test_stock库的undo_log表中,如果事务发生异常则进行回滚,并删除undo_log。整体的流程图如下图所示。
八、注意事项总结
1、注意spring cloud alibaba、nacos、seata-server依赖版本
2、加载数据源代理
这是AT模式的核心,只有使用了代理数据源才能实现分支事务的注册和回滚,不然不能实现分支事务的分布式处理。
以上为seata的AT模式详解,分享给大家,如有疑问,欢迎评论区留言讨论。