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 下管辖的全部分支事务完成提交或回滚请求。

安装seata
我们首先需要点击下载地址进行下载 Seata。
文件为: seata-server-1.3.0.zip
解压:
unzip seata-server-1.3.0.zip由于我们是使用 nacos 作为服务中心和配置中心,因此我们下载解压后需要做一些修改操作
1、编辑文件file.conf、registry.conf
进入 conf 目录编辑 registry.conf 和 file.conf 两个文件,编辑后内容如下
1.1 file.conf
file.conf 改指定参数
store {## store mode: file、db、redismode = "db"## database store propertydb {## 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 = 5maxConn = 30globalTable = "global_table"branchTable = "branch_table"lockTable = "lock_table"queryLimit = 100maxWait = 5000}}
1.2 registry.conf
registry.conf改指定参数registry {# file 、nacos 、eureka、redis、zk、consul、etcd3、sofatype = "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、etcd3type = "nacos"nacos {serverAddr = "127.0.0.1:8848"namespace = ""group = "SEATA_GROUP"username = "nacos"password = "essyParkNacos2021"}}
2、新增nacos-conf.sh 和 config.txt
- 由于新版 Seata 中没有
nacos-conf.sh和config.txt两个文件,因此我们需要独立下载:
config.txt就是seata各种详细的配置,执行nacos-config.sh即可将这些配置导入到nacos,这样就不需要将file.conf和registry.conf放到我们的项目中了,需要什么配置就直接从nacos中读取。
我们需要将 config.txt 文件放到 seata 目录下,而非 conf 目录下,并且需要修改 config.txt 内容
2.1、config.txt
config.txt改指定参数
transport.type=TCPtransport.server=NIOtransport.heartbeat=truetransport.enableClientBatchSendRequest=falsetransport.threadFactory.bossThreadPrefix=NettyBosstransport.threadFactory.workerThreadPrefix=NettyServerNIOWorkertransport.threadFactory.serverExecutorThreadPrefix=NettyServerBizHandlertransport.threadFactory.shareBossWorker=falsetransport.threadFactory.clientSelectorThreadPrefix=NettyClientSelectortransport.threadFactory.clientSelectorThreadSize=1transport.threadFactory.clientWorkerThreadPrefix=NettyClientWorkerThreadtransport.threadFactory.bossThreadSize=1transport.threadFactory.workerThreadSize=defaulttransport.shutdown.wait=3# 原来是service.vgroupMapping.my_test_tx_group,我改成service.vgroupMapping.hello_group (这句话修改完删掉)service.vgroupMapping.hello_group=defaultservice.default.grouplist=127.0.0.1:8091service.enableDegrade=falseservice.disableGlobalTransaction=falseclient.rm.asyncCommitBufferLimit=10000client.rm.lock.retryInterval=10client.rm.lock.retryTimes=30client.rm.lock.retryPolicyBranchRollbackOnConflict=trueclient.rm.reportRetryCount=5client.rm.tableMetaCheckEnable=falseclient.rm.sqlParserType=druidclient.rm.reportSuccessEnable=falseclient.rm.sagaBranchRegisterEnable=falseclient.tm.commitRetryCount=5client.tm.rollbackRetryCount=5client.tm.defaultGlobalTransactionTimeout=60000client.tm.degradeCheck=falseclient.tm.degradeCheckAllowTimes=10client.tm.degradeCheckPeriod=2000# store.mode=file改成 store.mode=db (这句话修改完删掉)store.mode=dbstore.file.dir=file_store/datastore.file.maxBranchSessionSize=16384store.file.maxGlobalSessionSize=512store.file.fileWriteBufferCacheSize=16384store.file.flushDiskMode=asyncstore.file.sessionReloadReadSize=100# db配置指向seata数据库 (这句话修改完删掉)store.db.datasource=druidstore.db.dbType=mysqlstore.db.driverClassName=com.mysql.jdbc.Driverstore.db.url=jdbc:mysql://127.0.0.1:3306/seata?useUnicode=truestore.db.user=rootstore.db.password=12345678store.db.minConn=5store.db.maxConn=30store.db.globalTable=global_tablestore.db.branchTable=branch_tablestore.db.queryLimit=100store.db.lockTable=lock_tablestore.db.maxWait=5000store.redis.host=127.0.0.1store.redis.port=6379store.redis.maxConn=10store.redis.minConn=1store.redis.database=0store.redis.password=nullstore.redis.queryLimit=100server.recovery.committingRetryPeriod=1000server.recovery.asynCommittingRetryPeriod=1000server.recovery.rollbackingRetryPeriod=1000server.recovery.timeoutRetryPeriod=1000server.maxCommitRetryTimeout=-1server.maxRollbackRetryTimeout=-1server.rollbackRetryTimeoutUnlockEnable=falseclient.undo.dataValidation=trueclient.undo.logSerialization=jacksonclient.undo.onlyCareUpdateColumns=trueserver.undo.logSaveDays=7server.undo.logDeletePeriod=86400000client.undo.logTable=undo_logclient.log.exceptionRate=100transport.serialization=seatatransport.compressor=nonemetrics.enabled=falsemetrics.registryType=compactmetrics.exporterList=prometheusmetrics.exporterPrometheusPort=9898
2.2、nacos-conf.sh
nacos-conf.sh不需要改放在conf 目录下
#!/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:" optdocase $opt inh)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;;esacdoneurlencode() {for ((i=0; i < ${#1}; i++))dochar="${1:$i:1}"case $char in[a-zA-Z0-9.~_-]) printf $char ;;*) printf '%%%02X' "'$char" ;;esacdone}if [[ -z ${host} ]]; thenhost=localhostfiif [[ -z ${port} ]]; thenport=8848fiif [[ -z ${group} ]]; thengroup="SEATA_GROUP"fiif [[ -z ${tenant} ]]; thentenant=""fiif [[ -z ${username} ]]; thenusername=""fiif [[ -z ${password} ]]; thenpassword=""finacosAddr=$host:$portcontentType="content-type:application/json;charset=UTF-8"echo "set nacosAddr=$nacosAddr"echo "set group=$group"failCount=0tempLog=$(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/nullif [[ -z $(cat "${tempLog}") ]]; thenecho " Please check the cluster status. "exit 1fiif [[ $(cat "${tempLog}") =~ "true" ]]; thenecho "Set $1=$2 successfully "elseecho "Set $1=$2 failure "(( failCount++ ))fi}count=0for line in $(cat $(dirname "$PWD")/config.txt | sed s/[[:space:]]//g); do(( count++ ))key=${line%%=*}value=${line#*=}addConfig "${key}" "${value}"doneecho "**=****=****=****=****=****=****=****=****=****=****=****=****=****=**==="echo " Complete initialization parameters, total-count:$count , failure-count:$failCount "echo "**=****=****=****=****=****=****=****=****=****=****=****=****=****=**==="if [[ ${failCount} -eq 0 ]]; thenecho " Init nacos config finished, please start seata-server. "elseecho " init nacos config fail. "fi
3、执行导入
在 conf 目录下执行
sh nacos-config.sh -h 127.0.0.1 (其中127.0.0.1是nacos地址)操作结束后,我们便可以在 nacos 控制台中看到配置列表,日后配置有需要修改便可以直接从这边修改,而不用修改目录文件:

4、数据库配置
在 1.3.0 最新版中依然没有 sql 文件,所以我们还是需要另外下载:sql 下载地址
新建seata数据库在 seata 数据中执行这个文件,生成三张表:
4.1、seata 库
-- -------------------------------- The script used when storeMode is 'db' ---------------------------------- the table to store GlobalSession dataCREATE 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 dataCREATE 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 dataCREATE 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 = INNODBAUTO_INCREMENT = 1DEFAULT CHARSET = utf8;5、启动seata
5.1编写启动脚本
做好了以上准备,我们便可以启动 seata 了,直接在 bin 目录下 cmd 执行 bat 脚本即可,启动结束便可在 nacos 中看到 seata 服务:
新建start.sh,并存放在seata根目录下

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代理数据源
@Configurationpublic 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 + 服务名称 = defaultgroup为: SEATA_GROUP
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常见问题及解决
- 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=false1.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 = INNODBAUTO_INCREMENT = 1DEFAULT 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无法判断存储过程进行了什么操作
如果这篇文章对你有帮助,欢迎分享给更多人!
部分信息可能已经过时

