一、开发环境
nacos 2.0.3
seata1.6.1
二、下载seata
官方下载地址:https://github.com/seata/seata/releases
下载版本与springcloud alibaba和nacos版本对应关系:版本说明 · alibaba/spring-cloud-alibaba Wiki · GitHub
三、简单使用
1、下载后为此压缩包, 解压得到seata文件夹
2、seata服务端配置相关
打开conf文件夹
只需要关注application.yml与application.example.yml即可
其中application.yml为真正的配置文件,application.example.yml为配置文件的模板
关注application.example.yml中的如下即可:
把这两段配置文件模板中的配置复制到application.yml中对应位置即可
注意type改为nacos
application.yml可以参考我的:
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:
# support: nacos, consul, apollo, zk, etcd3
type: nacos
nacos:
server-addr: xxxx #nacos地址
namespace: xxxx #命名空间
group: DEFAULT_GROUP
username: nacos
password: nacos
context-path:
##if use MSE Nacos with auth, mutex with username/password attribute
#access-key:
#secret-key:
data-id: seataServer.properties
registry:
# support: nacos, eureka, redis, zk, consul, etcd3, sofa
type: nacos
nacos:
application: seata-server #seata启动后在nacos的服务名
server-addr: xxxx #nacos地址
group: DEFAULT_GROUP
namespace: xxxx #命名空间
cluster: default
username: nacos
password: nacos
store:
# support: file 、 db 、 redis
mode: file
# 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、手动注册seata服务端到nacos
新建nacos上seata的配置
对应关系如上,配置的具体内容在
mysql相关只有这一段
全部配置文件可以参考我的
#For details about configuration items, see https://seata.io/zh-cn/docs/user/configurations.html
#Transport configuration, for client and server
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
#These configurations are required if the `store mode` is `db`. If `store.mode,store.lock.mode,store.session.mode` are not equal to `db`, you can remove the configuration block.
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=banmajio
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
#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
store.mode默认为file,改为db
记得修改数据库信息为自己的,nacos上的配置文件和seata\script\config-center\config.txt中都要修改!!!
service.vgroupMapping.xxxx
后边xxxx可以自定义
参考我的 service.vgroupMapping.mygroup=default
对应yml中
4、seata运行所需数据库
先建数据库:我的是hyb3_seata
官方提供了生成表的sql!
运行上面sql文件生成四张表
所有业务数据库也都要表undo_log!!!
运行下面sql即可
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服务端
此位置下双击运行seata-server.bat
后在nacos的对应namespace下可以看到在运行的seata了
6、复现没有seata(分布式事务)时产生的问题
开始时候的数据库,del为0表示未删除
如下图操作,有除以0异常
即使有除以0的异常也无法回滚,养殖场还是被删除掉了,
7、Seata Client搭建
在微服务的pom.xml中添加如下配置(不是父类中,是每个需要的子微服务中)
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-seata</artifactId>
<version>你的springcloud版本</version>
</dependency>
<dependency>
<groupId>io.seata</groupId>
<artifactId>seata-spring-boot-starter</artifactId>
<version>1.6.1</version>
</dependency>
后在你调用地方的controller处添加注解@GlobalTransactional 即可,后面调用的feign不需要@GlobalTransactional与@Transactional
启动微服务可以在seata服务端看到注册上去的微服务信息
此时调用接口即实现分布式事务,无论调用方还是被调用方出现问题都会回滚!
8、linux服务器部署
①、服务器新建文件夹seata
mkdir seata
②、然后把如下文件夹复制进上面服务器创建好的seata文件夹中
③、之后进入bin文件夹给.sh授权
chmod +x *.sh
④、后直接运行如下即可启动
sh seata-server.sh -h 127.0.0.1 -p 8091 -m db
具体启动命令每个参数的意思可以看官方文档:Seata部署指南
9、常见问题
1、未传递xid,没有回滚
首先检查两个服务之间xid是否一致
String xid = RootContext.getXID();
两边打印xid,对比判断是否一致
如果没有传递参考处理 Seata分布式事务中 没有传递XID 导致事务失效的问题_seata xid-CSDN博客
2、调用feign异常,没有回滚
检查项目是否有全局处理异常,
或者是否异常被feign自己try catch处理了
异常一定不要子去处理,要丢该父,让父报错才会回滚
3、实在不行,手动回滚
GlobalTransactionContext.reload(RootContext.getXID()).rollback();
4、部署服务器报错[io.seata.core.store.db.DataSourceProvider] name is null
具体可以看我写的另外一篇文章:关于seata1.6.1部署linux服务器后[io.seata.core.store.db.DataSourceProvider] name is null报错-CSDN博客