分布式事务框架 Seata 入门案例
1. Seata Server 部署
Seata分TC、TM和RM三个角色,TC(Server端)为单独服务端部署,TM和RM(Client端)由业务系统集成。
首先,下载最新的安装包
也可以下载源码,然后本地编译。最新的版本是1.5.2
下载后的启动包(或者源码)中有个scripts目录,里面有各种我们所需的脚本
Server端存储模式(store.mode)现有file、db、redis三种:
- file模式为单机模式,全局事务会话信息内存中读写并持久化本地文件root.data,性能较高;(不推荐)
- db模式为高可用模式,全局事务会话信息通过db共享,相应性能差些;
- redis模式Seata-Server 1.3及以上版本支持,性能较高,存在事务信息丢失风险,请提前配置合适当前场景的redis持久化配置;
修改配置文件
- 启动包:seata–>conf–>application.yml
- 源码包:根目录–>seata-server–>resources–>application.yml
主要修改的点是:
- 修改store.mode=”db或者redis”
- 修改seata.config、seata.registry
- 修改数据库连接|redis属性配置
在资源目录还有一个application.example.yml文件,application.example.yml中附带额外配置,可以将其db|redis相关配置复制至application.yml,进行修改store.db或store.redis相关属性。
如果不使用外部配置中心,直接使用本地文件配置的话,那么最简单的配置可能是这样的:
server:
port: 7091
spring:
application:
name: seata-server
logging:
config: classpath:logback-spring.xml
file:
path: ${user.home}/logs/seata
extend:
logstash-appender:
destination: 127.0.0.1:4560
kafka-appender:
bootstrap-servers: 127.0.0.1:9092
topic: logback_to_logstash
console:
user:
username: seata
password: seata
seata:
config:
type: file
registry:
type: nacos
nacos:
application: seata-server
server-addr: 127.0.0.1:8848
group: SEATA_GROUP
namespace:
cluster: default
store:
mode: db
db:
datasource: druid
db-type: mysql
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/seata?rewriteBatchedStatements=true&useUnicode=true&serverTimezone=Asia/Shanghai
user: root
password: 123456
min-conn: 5
max-conn: 100
global-table: global_table
branch-table: branch_table
lock-table: lock_table
distributed-lock-table: distributed_lock
query-limit: 100
max-wait: 5000
security:
secretKey: SeataSecretKey0c382ef121d778043159209298fd40bf3850a017
tokenValidityInMilliseconds: 1800000
ignore:
urls: /,/**/*.css,/**/*.js,/**/*.html,/**/*.map,/**/*.svg,/**/*.png,/**/*.ico,/console-fe/public/**,/api/v1/auth/login
更多配置请参见 https://seata.io/zh-cn/docs/user/configurations.html
这里面哪些是Server端需要配置的,哪些是Client端需要配置的,以及每个参数的含义都解释得非常详细,强烈建议看一下,这里就不在赘述。
此处注册中心用nacos
https://nacos.io/zh-cn/index.html
建表(默认数据库是seata)
USE `seata`;
-- -------------------------------- 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 COMMENT = "全局事务表";
-- 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(6),
`gmt_modified` DATETIME(6),
PRIMARY KEY (`branch_id`),
KEY `idx_xid` (`xid`)
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COMMENT = "分支事务表";
-- 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 COMMENT = "全局锁表";
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);
如果采用AT模式,那么每个业务数据库还需建一个undo_log表
-- 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 NOT NULL COMMENT "branch transaction id",
`xid` VARCHAR(128) 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 = utf8mb4 COMMENT ="AT transaction mode undo table";
启动
- 源码启动: 执行ServerApplication.java的main方法
- 命令启动: seata-server.sh -h 127.0.0.1 -p 8091 -m db
- -h: 注册到注册中心的ip
- -p: Server rpc 监听端口
- -m: 全局事务会话信息存储模式,file、db、redis,优先读取启动参数
- -n: Server node,多个Server时,需区分各自节点,用于生成不同区间的transactionId,以免冲突
- -e: 多环境配置参考 http://seata.io/en-us/docs/ops/multi-configuration-isolation.html
2. 业务系统集成 Seata Client
步骤一:添加seata依赖(建议单选)
- 依赖seata-all
- 依赖seata-spring-boot-starter,支持yml、properties配置(.conf可删除),内部已依赖seata-all
- 依赖spring-cloud-alibaba-seata,内部集成了seata,并实现了xid传递
步骤二:undo_log建表、配置参数(仅AT模式)
https://seata.io/zh-cn/docs/user/configurations.html
步骤三:数据源代理(不支持自动和手动配置并存)
1、如果使用seata-all
自动配置由注解@EnableAutoDataSourceProxy开启,并可选择jdk proxy或者cglib proxy。
如果采用XA模式,@EnableAutoDataSourceProxy(dataSourceProxyMode = “XA”)
手动配置参考如下:
@Primary
@Bean("dataSource")
public DataSource dataSource(DataSource druidDataSource) {
//AT 代理 二选一
return new DataSourceProxy(druidDataSource);
//XA 代理
return new DataSourceProxyXA(druidDataSource)
}
2、如果使用seata-starter
默认就开启了自动代理数据源,无需额外配置
如果使用自动代理数据源时,如果使用XA模式还需要调整配置文件application.yml
seata:
data-source-proxy-mode: XA
如果想要关闭seata-spring-boot-starter的数据源自动代理,可调整配置文件application.yml
seata:
enable-auto-data-source-proxy: false
步骤四:初始化GlobalTransactionScanner
自动,引入seata-spring-boot-starter、spring-cloud-starter-alibaba-seata等jar即可
手动
@Bean
public GlobalTransactionScanner globalTransactionScanner() {
String applicationName = this.applicationContext.getEnvironment().getProperty("spring.application.name");
String txServiceGroup = this.seataProperties.getTxServiceGroup();
if (StringUtils.isEmpty(txServiceGroup)) {
txServiceGroup = applicationName + "-fescar-service-group";
this.seataProperties.setTxServiceGroup(txServiceGroup);
}
return new GlobalTransactionScanner(applicationName, txServiceGroup);
}
步骤五:业务使用
只需在业务方法上加上@GlobalTransactional 注解即可
3. 示例代码
此处用官网的那个案例,调用关系如图:
首先,建库建表,脚本如下:
SQL脚本
CREATE DATABASE `account`;
USE `account`;
DROP TABLE IF EXISTS `t_account`;
CREATE TABLE `t_account` (
`id` int NOT NULL AUTO_INCREMENT,
`user_id` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`amount` double(14,2) DEFAULT "0.00",
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
INSERT INTO `t_account` VALUES (1,"1",79.90);
DROP TABLE IF EXISTS `undo_log`;
CREATE TABLE `undo_log` (
`branch_id` bigint NOT NULL COMMENT "branch transaction id",
`xid` varchar(128) 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 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 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT="AT transaction mode undo table";
CREATE DATABASE `order`;
USE `order`;
DROP TABLE IF EXISTS `t_order`;
CREATE TABLE `t_order` (
`id` int NOT NULL AUTO_INCREMENT,
`order_no` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`user_id` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`commodity_code` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`count` int DEFAULT "0",
`amount` double(14,2) DEFAULT "0.00",
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
DROP TABLE IF EXISTS `undo_log`;
CREATE TABLE `undo_log` (
`branch_id` bigint NOT NULL COMMENT "branch transaction id",
`xid` varchar(128) 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 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 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT="AT transaction mode undo table";
CREATE DATABASE `stock`;
USE `stock`;
DROP TABLE IF EXISTS `t_stock`;
CREATE TABLE `t_stock` (
`id` int NOT NULL AUTO_INCREMENT,
`commodity_code` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`count` int DEFAULT "0",
PRIMARY KEY (`id`),
UNIQUE KEY `commodity_code` (`commodity_code`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
INSERT INTO `t_stock` VALUES (1,"A001","立白洗洁精",7);
DROP TABLE IF EXISTS `undo_log`;
CREATE TABLE `undo_log` (
`branch_id` bigint NOT NULL COMMENT "branch transaction id",
`xid` varchar(128) 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 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 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT="AT transaction mode undo table";
注意版本:示例中使用的框架为 Spring Boot + Mybatis-Plus + Dubbo + Seata
虽然Seata最新版本是1.5.2,Dubbo最新版本为3.1.1,但这这两个版本中二者不兼容,可以降低其中一个的版本,比如
Seata 1.4.2 + Dubbo 3.1.1 或者 Seata 1.5.2 + Dubbo 2.7.18
本示例中采用的是 seata-spring-boot-starter 1.5.2 + dubbo 2.7.18
工程结构如图
父pom.xml如下
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.cjs.example</groupId>
<artifactId>seata-spring-boot-starter-samples</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<name>seata-spring-boot-starter-samples</name>
<modules>
<module>samples-common-service</module>
<module>samples-stock-service</module>
<module>samples-order-service</module>
<module>samples-account-service</module>
<module>samples-business-service</module>
</modules>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring-boot.version>2.7.5</spring-boot.version>
<dubbo.version>2.7.18</dubbo.version>
<seata.version>1.5.2</seata.version>
<mybatis-plus.version>3.5.2</mybatis-plus.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!--
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-dependencies-bom</artifactId>
<version>${dubbo.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
-->
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo</artifactId>
<version>${dubbo.version}</version>
</dependency>
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-spring-boot-starter</artifactId>
<version>${dubbo.version}</version>
</dependency>
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-registry-nacos</artifactId>
<version>${dubbo.version}</version>
</dependency>
<dependency>
<groupId>io.seata</groupId>
<artifactId>seata-spring-boot-starter</artifactId>
<version>${seata.version}</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatis-plus.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
</project>
子pom.xml如下,其它几个类似不再重复:
<?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.cjs.example</groupId>
<artifactId>seata-spring-boot-starter-samples</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<groupId>com.cjs.example</groupId>
<artifactId>samples-order-service</artifactId>
<version>${parent.version}</version>
<name>samples-order-service</name>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>com.cjs.example</groupId>
<artifactId>samples-common-service</artifactId>
<version>${parent.version}</version>
</dependency>
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo</artifactId>
</dependency>
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-registry-nacos</artifactId>
</dependency>
<dependency>
<groupId>io.seata</groupId>
<artifactId>seata-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</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: 8083
servlet:
context-path: /order
spring:
application:
name: samples-order-service
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/order?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
username: root
password: 123456
dubbo:
protocol:
name: dubbo
port: 20883
registry:
address: nacos://127.0.0.1:8848
config-center:
address: nacos://127.0.0.1:8848
metadata-report:
address: nacos://127.0.0.1:8848
seata:
enabled: true
tx-service-group: my_test_tx_group
service:
vgroup-mapping:
my_test_tx_group: default
registry:
type: nacos
nacos:
server-addr: 127.0.0.1:8848
cluster: default
group: SEATA_GROUP
核心代码如下
依次启动这四个项目,Postman访问一下
通过断点,观察 global_table、lock_table、branch_table 等表数据的变化
刚开始,所有表中数据都是空的
执行到事务方法之后,global_table表中有了一条数据
当调用第一个远程接口扣减库存后,lock_table和branch_table表中都有了一条数据
同时,stock库中undo_log表中也新增了一条数据
继续往下执行,当调用第二个远程接口创建订单后,branch_table和lock_table中都新增了2条数据
account库和order库中的undo_log也有了数据
当事务方法执行完后,事务提交,上述表中此次事务相关数据清空
我们通过Seata Server的日志可以更清晰的看到事务从创建到提交的整个过程
正式正常事务成功的情况,有时候由于业务报错了,或者事务超时了,或者其它的情况,事务会回滚
4. 配置中心
在此之前,示例中没有使用配置中心,而是采用本地配置文件的方式。但实际开发过程中,建议还是采用配置中心,下面以nacos作为配置中心演示。
细心的同学会发现,微服务架构中有配置中心和注册中心,Dubbo中也有配置中心和注册中心,而本文讲的Seata也有配置中心和注册中心。那么它们有什么区别吗?其实,并没有区别,各是各的。微服务的配置中心和注册中心你要配置,Dubbo的你也要配置,Seata的配置中心和注册中心你还要配置,尽管它们可能是同一个实例,但那也得各配各的。
<dependency>
<groupId>com.alibaba.nacos</groupId>
<artifactId>nacos-client</artifactId>
<version>2.1.1</version>
</dependency>
有两种配置方式
方式一:放在某个命名空间下,每一个配置项作为一行,即每一行一个DataId
https://github.com/seata/seata/tree/master/script/config-center
在scripts/config-center目录下有个config.txt,这个config.txt文件中为我们准备好了各种配置项,我们按需修改里面的内容即可,然后可以通过脚本将config.txt中的内容导入nacos,当然也可以一条一条手动在nacos中创建
例如:
sh ${SEATAPATH}/script/config-center/nacos/nacos-config.sh -h localhost -p 8848 -g SEATA_GROUP -t 5a3c7d6c-f497-4d68-a71a-2e5e3340b3ca -u username -w password
注意:-g 指定Group -t 指定命名空间
示例中上传到默认命名空间下了
注意,config.txt中包含了Server端和Client端的配置,里面注释写的也比较清楚哪些是Server端需要的配置,哪些是Client端的配置
导入配置以后,现在修改Server端的配置,seata–>conf–>application.yml中seata.config部分
seata:
config:
type: nacos
nacos:
server-addr: 127.0.0.1:8848
group : "SEATA_GROUP"
namespace:
username:
password:
同时,每个业务系统里面的配置也要修改一下
seata:
config:
type: nacos
nacos:
server-addr: 127.0.0.1:8848
group : "SEATA_GROUP"
namespace:
username:
password:
由于这里导入配置的时候没有-t指定命名空间,即导入到默认命名空间,所以配置里面namespace为空,如果-t指定了特定的命名空间,则server和client端的namespace也要与之对应
方式二:通过dataId配置
首先,需要在nacos新建配置,此处dataId为seataServer.properties
然后,将修改后的config.txt内容粘贴进去,保存修改并发布即可
修改Server和Client端seata.config配置
seata:
config:
type: nacos
nacos:
server-addr: 127.0.0.1:8848
group: "SEATA_GROUP"
namespace:
dataId: "seataServer.properties"
username:
password:
重启Server和Client即可