1399 字
4 分钟
SpringCloud Seata:分布式事务解决方案

seata概述#

分布式事务处理过程的ID+三组件模型

全局事务ID

TransactionID XID

三个角色

  • Transaction Coordinator(TC): Maintain status of global and branch transactions, drive the global commit or rollback.

    事务协调器,维护全局事务的运行状态,负责协调并驱动全局事务的提交或回滚;

  • Transaction Manager(TM): Define the scope of global transaction: begin a global transaction, commit or rollback a global transaction.

    控制全局事务的边界,负责开启一个全局事务,并最终发起全局提交或全局回滚的决议;

  • Resource Manager(RM): Manage resources that branch transactions working on, talk to TC for registering branch transactions and reporting status of branch transactions, and drive the branch transaction commit or rollback.

    控制分支事务,负责分支注册、状态汇报,并接收事务协调器的指令,驱动分支(本地)事务的提交和回滚

TM 向 TC 申请开启一个全局事务,全局事务创建成功并生成一个全局唯一的 XID; XID 在微服务调用链路的上下文中传播; RM 向 TC 注册分支事务,将其纳入 XID 对应全局事务的管辖; TM 向 TC 发起针对 XID 的全局提交或回滚决议; TC 调度 XID 下管辖的全部分支事务完成提交或回滚请求。

image-20220220152818271

安装seata#

我们首先需要点击下载地址进行下载 Seata

文件为: seata-server-1.3.0.zip

解压:

unzip seata-server-1.3.0.zip

由于我们是使用 nacos 作为服务中心和配置中心,因此我们下载解压后需要做一些修改操作

1、编辑文件file.conf、registry.conf#

进入 conf 目录编辑 registry.conffile.conf 两个文件,编辑后内容如下

1.1 file.conf#

file.conf 改指定参数

store {
## store mode: file、db、redis
mode = "db"
## database store property
db {
## the implement of javax.sql.DataSource, such as DruidDataSource(druid)/BasicDataSource(dbcp)/HikariDataSource(hikari) etc.
datasource = "druid"
## mysql/oracle/postgresql/h2/oceanbase etc.
dbType = "mysql"
driverClassName = "com.mysql.jdbc.Driver"
url = "jdbc:mysql://127.0.0.1:3306/seata"
user = "root"
password = "easyParkMysql2021"
minConn = 5
maxConn = 30
globalTable = "global_table"
branchTable = "branch_table"
lockTable = "lock_table"
queryLimit = 100
maxWait = 5000
}
}

1.2 registry.conf#

registry.conf 改指定参数

registry {
# file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
type = "nacos"
nacos {
application = "seata-server"
serverAddr = "127.0.0.1:8848"
group = "SEATA_GROUP"
namespace = ""
cluster = "default"
username = "nacos"
password = "essyParkNacos2021"
}
}
config {
# file、nacos 、apollo、zk、consul、etcd3
type = "nacos"
nacos {
serverAddr = "127.0.0.1:8848"
namespace = ""
group = "SEATA_GROUP"
username = "nacos"
password = "essyParkNacos2021"
}
}

2、新增nacos-conf.shconfig.txt#

  • 由于新版 Seata 中没有 nacos-conf.shconfig.txt 两个文件,因此我们需要独立下载:

nacos-config.sh 下载地址

config.txt 下载地址

config.txt就是seata各种详细的配置,执行 nacos-config.sh 即可将这些配置导入到nacos,这样就不需要将file.confregistry.conf放到我们的项目中了,需要什么配置就直接从nacos中读取。

我们需要将 config.txt 文件放到 seata 目录下,而非 conf 目录下,并且需要修改 config.txt 内容

2.1、config.txt#

config.txt 改指定参数

image-20210425155521861

transport.type=TCP
transport.server=NIO
transport.heartbeat=true
transport.enableClientBatchSendRequest=false
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
# 原来是service.vgroupMapping.my_test_tx_group,我改成service.vgroupMapping.hello_group (这句话修改完删掉)
service.vgroupMapping.hello_group=default
service.default.grouplist=127.0.0.1:8091
service.enableDegrade=false
service.disableGlobalTransaction=false
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=false
client.rm.sqlParserType=druid
client.rm.reportSuccessEnable=false
client.rm.sagaBranchRegisterEnable=false
client.tm.commitRetryCount=5
client.tm.rollbackRetryCount=5
client.tm.defaultGlobalTransactionTimeout=60000
client.tm.degradeCheck=false
client.tm.degradeCheckAllowTimes=10
client.tm.degradeCheckPeriod=2000
# store.mode=file改成 store.mode=db (这句话修改完删掉)
store.mode=db
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
# db配置指向seata数据库 (这句话修改完删掉)
store.db.datasource=druid
store.db.dbType=mysql
store.db.driverClassName=com.mysql.jdbc.Driver
store.db.url=jdbc:mysql://127.0.0.1:3306/seata?useUnicode=true
store.db.user=root
store.db.password=12345678
store.db.minConn=5
store.db.maxConn=30
store.db.globalTable=global_table
store.db.branchTable=branch_table
store.db.queryLimit=100
store.db.lockTable=lock_table
store.db.maxWait=5000
store.redis.host=127.0.0.1
store.redis.port=6379
store.redis.maxConn=10
store.redis.minConn=1
store.redis.database=0
store.redis.password=null
store.redis.queryLimit=100
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
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.log.exceptionRate=100
transport.serialization=seata
transport.compressor=none
metrics.enabled=false
metrics.registryType=compact
metrics.exporterList=prometheus
metrics.exporterPrometheusPort=9898

2.2、nacos-conf.sh#

nacos-conf.sh 不需要改

放在conf 目录下

image-20210425160358879

#!/usr/bin/env bash
# Copyright 1999-2019 Seata.io Group.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at、
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
while getopts ":h:p:g:t:u:w:" opt
do
case $opt in
h)
host=$OPTARG
;;
p)
port=$OPTARG
;;
g)
group=$OPTARG
;;
t)
tenant=$OPTARG
;;
u)
username=$OPTARG
;;
w)
password=$OPTARG
;;
?)
echo " USAGE OPTION: $0 [-h host] [-p port] [-g group] [-t tenant] [-u username] [-w password] "
exit 1
;;
esac
done
urlencode() {
for ((i=0; i < ${#1}; i++))
do
char="${1:$i:1}"
case $char in
[a-zA-Z0-9.~_-]) printf $char ;;
*) printf '%%%02X' "'$char" ;;
esac
done
}
if [[ -z ${host} ]]; then
host=localhost
fi
if [[ -z ${port} ]]; then
port=8848
fi
if [[ -z ${group} ]]; then
group="SEATA_GROUP"
fi
if [[ -z ${tenant} ]]; then
tenant=""
fi
if [[ -z ${username} ]]; then
username=""
fi
if [[ -z ${password} ]]; then
password=""
fi
nacosAddr=$host:$port
contentType="content-type:application/json;charset=UTF-8"
echo "set nacosAddr=$nacosAddr"
echo "set group=$group"
failCount=0
tempLog=$(mktemp -u)
function addConfig() {
curl -X POST -H "${contentType}" "http://$nacosAddr/nacos/v1/cs/configs?dataId=$(urlencode $1)&group=$group&content=$(urlencode $2)&tenant=$tenant&username=$username&password=$password" >"${tempLog}" 2>/dev/null
if [[ -z $(cat "${tempLog}") ]]; then
echo " Please check the cluster status. "
exit 1
fi
if [[ $(cat "${tempLog}") =~ "true" ]]; then
echo "Set $1=$2 successfully "
else
echo "Set $1=$2 failure "
(( failCount++ ))
fi
}
count=0
for line in $(cat $(dirname "$PWD")/config.txt | sed s/[[:space:]]//g); do
(( count++ ))
key=${line%%=*}
value=${line#*=}
addConfig "${key}" "${value}"
done
echo "**=****=****=****=****=****=****=****=****=****=****=****=****=****=**==="
echo " Complete initialization parameters, total-count:$count , failure-count:$failCount "
echo "**=****=****=****=****=****=****=****=****=****=****=****=****=****=**==="
if [[ ${failCount} -eq 0 ]]; then
echo " Init nacos config finished, please start seata-server. "
else
echo " init nacos config fail. "
fi

3、执行导入#

conf 目录下执行

sh nacos-config.sh -h 127.0.0.1 (其中127.0.0.1是nacos地址)

操作结束后,我们便可以在 nacos 控制台中看到配置列表,日后配置有需要修改便可以直接从这边修改,而不用修改目录文件:

image-20210425161637145

4、数据库配置#

1.3.0 最新版中依然没有 sql 文件,所以我们还是需要另外下载:sql 下载地址

新建seata数据库在 seata 数据中执行这个文件,生成三张表:

4.1、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_gmt_modified_status` (`gmt_modified`, `status`),
KEY `idx_transaction_id` (`transaction_id`)
) ENGINE = InnoDB
DEFAULT CHARSET = utf8;
-- 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 = utf8;
-- the table to store lock data
CREATE TABLE IF NOT EXISTS `lock_table`
(
`row_key` VARCHAR(128) NOT NULL,
`xid` VARCHAR(96),
`transaction_id` BIGINT,
`branch_id` BIGINT NOT NULL,
`resource_id` VARCHAR(256),
`table_name` VARCHAR(32),
`pk` VARCHAR(36),
`gmt_create` DATETIME,
`gmt_modified` DATETIME,
PRIMARY KEY (`row_key`),
KEY `idx_branch_id` (`branch_id`)
) ENGINE = InnoDB
DEFAULT CHARSET = utf8;

4.2 业务数据库#

在我们的业务数据库中执行 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
AUTO_INCREMENT = 1
DEFAULT CHARSET = utf8;

5、启动seata#

5.1编写启动脚本#

做好了以上准备,我们便可以启动 seata 了,直接在 bin 目录下 cmd 执行 bat 脚本即可,启动结束便可在 nacos 中看到 seata 服务:

新建start.sh,并存放在seata根目录下

image-20210425162137590

nohup ./bin/seata-server.sh -p 8091 -h 8.135.57.242 -m file >nohup.out 2>1 &

5.2启动#

sh start.sh

项目中集成seata#

在 Seata 安装的步骤中我们便完成了 Seata 服务端 的启动安装,接下来就是在项目中集成 Seata 客户端

1、添加依赖#

我们需要在 pom.xml 文件中添加两个依赖:seata 依赖

<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-seata</artifactId>
<exclusions>
<!-- 排除依赖 指定版本和服务器端一致 -->
<exclusion>
<groupId>io.seata</groupId>
<artifactId>seata-all</artifactId>
</exclusion>
<exclusion>
<groupId>io.seata</groupId>
<artifactId>seata-spring-boot-starter</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.seata</groupId>
<artifactId>seata-all</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>io.seata</groupId>
<artifactId>seata-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
<!--druid,解决mybatisPLus和seata3.0连接池不对应导致localdatetime转换失败-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.21</version>
</dependency>
<!--druid连接池-->

注意: 这里需要排除 spring-cloud-starter-alibaba-seata 自带的 seata 依赖,然后引入我们自己需要的 seata 版本,如果版本不一致启动时可能会造成 no available server to connect 错误!

2、需要自己配置seata代理数据源#

@Configuration
public class DataSourceProxyConfig {
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DruidDataSource druidDataSource() {
return new DruidDataSource();
}
@Primary
@Bean
public DataSourceProxy dataSource(DruidDataSource druidDataSource) {
return new DataSourceProxy(druidDataSource);
}
}

配置完数据源我们得在启动类的 SpringBootApplication 上排除Druid数据源依赖,否则可能会出现循环依赖的错误:

  • @EnableAutoDataSourceProxy
  • (exclude = {DataSourceAutoConfiguration.class})
//此注解是开启数据源自动代理
@EnableAutoDataSourceProxy
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})

3、配置事务组项#

nacos 的配置文件控制台中加入我们服务的事务组项:

如不想添加,也可以在文件(config.txt)中指定,添加内容如下

service.vgroupMapping.hello_group=default

service.vgroupMapping + 服务名称 = default
group为: SEATA_GROUP

image-20210425163007209

4、项目中配置修改#

application.yml配置

spring:
profiles:
active: dev
cloud:
alibaba:
seata:
#这个要全局唯一,这个是前面在config.txt中的service.vgroupMapping.my_test_tx_group=default
#修改为service.vgroupMapping.hello_group=default。
tx-service-group: hello_group
#seata配置
seata:
enabled: true
#可以随意,现在设置成应用名
application-id: ${spring.application.name}
#事务组 这里的名字与config.txt中vgroup_mapping.my_test_tx_group = "default"相同
tx-service-group: hello_group
enable-auto-data-source-proxy: true
#use-jdk-proxy: false
service:
#事务组 这里的名字与config.txt中vgroup_mapping.my_test_tx_group = "default"相同
vgroup-mapping:
my_test_tx_group: hello_group
#这里的名字与config.txt中default.grouplist = "127.0.0.1:8091"相同
grouplist:
default: 8.135.57.242:8091
#disable-global-transaction: false
config:
type: nacos
nacos:
#这里的地址就是你的nacos的地址,可以更换为线上
serverAddr: 8.135.57.242:8848
#这里的名字就是registry.conf中 nacos的group名字
group: SEATA_GROUP
userName: "nacos"
password: "essyParkNacos2021"
registry:
type: nacos
nacos:
application: seata-server
#这里的地址就是你的nacos的地址,可以更换为线上
server-addr: 8.135.57.242:8848
#这里的名字就是registry.conf中 nacos的group名字
group: SEATA_GROUP
userName: "nacos"
password: "essyParkNacos2021"

5、开启全局事务#

这步就是最终一步了,在我们需要开启事务的方法上添加 @GlobalTransactional 注解,类似于我们单体事务添加的@Transactional

user服务#

调用并开始全局事务

@Autowired
private ThirdFeignClient thirdFeignClient;
@GlobalTransactional(name = "testSeata",rollbackFor = Exception.class)
@GetMapping("/testSeata")
public void test(){
log.info("开始保存");
thirdFeignClient.test();
log.info("手工抛出异常");
throw new EpException(ServiceCodeEnum.BAD_REQUEST);
}

third服务#

提供服务

@GetMapping(value = "/test")
public void test(){
savePictureValidationCode("我就是ip","我就是uuid","我就是code","base64");
}
/**
* 保存数据
*
* @param addressIp 请求的ip
* @param uuid uuid
* @param rightCode 验证码正确的内容
*/
private void savePictureValidationCode(String addressIp, String uuid, String rightCode, String imgBase64String) {
PictureValidationCodeDO codeDO = new PictureValidationCodeDO();
codeDO.setRightCode(rightCode);
codeDO.setAddressIp(addressIp);
codeDO.setUuid(uuid);
codeDO.setImgBase64(imgBase64String);
validateCodeService.save(codeDO);
}

openfiegn

@FeignClient(value = "third")
public interface ThirdFeignClient {
/**
* 校验验证码
*/
@PostMapping(value = "/kaptcha/validate")
JsonResultVO<String> validate(@RequestBody ValidateCheckRequest checkRequest);
@GetMapping(value = "/kaptcha/test")
void test();
}

6、注意事项#

seata常见问题及解决

  1. seata 1.1 Caused by: io.seata.common.exception.NotSupportYetException: aa_bb_record needs to contain the primary key.

seata 全局事务报业务表(postgresql 序列主键) 需要包含primary key

解决: 多数据源配置 seata.enable-auto-data-source-proxy=false 单个数据源配置 seata.enable-auto-data-source-proxy=true

seata.enable-auto-data-source-proxy=false

1.2 io.seata.common.exception.NotSupportYetException: undo_log needs to contain the primary key.

seata1.2.0 全局事务报undo_log 需要包含primary key

解决: 官方undo_log ddl 参考 加了自增id后的ddl如下:

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
AUTO_INCREMENT = 1
DEFAULT CHARSET = utf8;

1.Caused by: io.seata.common.exception.NotSupportYetException: MZSF.MZYS_TBS_DPRESP needs to contain the primary key.

或者 TCC模式 下报io.seata.common.exception.NotSupportYetException: multi pk only support mysql !

原因:@GlobalTransactional和@Transactional不一起使用,解决方案:去除@Transactional 或者 使用 saveAndFlush

2.ArrayIndexOutOfBoundsException: 22/4001

原因:AT模式Jpa saveAll报数组越界, 改成循环saveAndFlush

3.@BusinessActionContextParameter会将参数存在branch表,不必担心数据丢失

4.复合主键进行删除操作时先将删除的对象查询出来,可存在@BusinessActionContextParameter,用于二阶段回滚时使用

5.seata无法调用存储过程,原因:seata无法判断存储过程进行了什么操作

分享

如果这篇文章对你有帮助,欢迎分享给更多人!

SpringCloud Seata:分布式事务解决方案
https://onecodemaker.cn/posts/springcloud-07-seata/
作者
糖糖IT
发布于
2026-03-20
许可协议
CC BY-NC-SA 4.0

部分信息可能已经过时

目录