在微服务中,单体注解@Transactional是本地事务,就不再适用了,需要采用分布式事务。而Seata就是一款分布式事务解决方案。
1、下载
下载地址
本文选择1.6.0版本。
下载解压后目录:
2、配置服务端
本文是使用nacos作为seata的注册中心和配置中心,所以先在nacos中创建seata的命名空间
2.1、yml配置
在seata-server-1.6.0\seata\conf目录下找到application.yml,参照application.example.yml配置如下
server:
port: 7091
spring:
application:
name: seata-server
logging:
#config: classpath:logback-spring.xml
file:
path: ${user.home}/logs/seata
console:
user:
username: seata
password: seata
seata:
config:
# support: nacos, consul, apollo, zk, etcd3
type: nacos
nacos:
server-addr: 127.0.0.1:8848
namespace: 86ab3ca5-81db-4efb-ae22-7b4a2980a96b
group: SEATA_GROUP
username: nacos
password: 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: 86ab3ca5-81db-4efb-ae22-7b4a2980a96b
cluster: default
username: nacos
password: nacos
store:
# support: file 、 db 、 redis
mode: db
db:
datasource: druid
db-type: mysql
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://192.168.200.139:3306/sxxc_seata?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
user: root
password: root
min-conn: 10
max-conn: 100
global-table: global_table
branch-table: branch_table
lock-table: lock_table
distributed-lock-table: distributed_lock
query-limit: 1000
max-wait: 5000
# 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
其中主要配置才seata:config、seata:registry、seata:store
- config:是配置配置中心相关的配置。将seata.config.type修改成nacos
- type:可选 nacos, consul, apollo, zk, etcd3,本文使用nacos
config:
# support: nacos, consul, apollo, zk, etcd3
type: nacos
nacos:
server-addr: 127.0.0.1:8848
namespace: 86ab3ca5-81db-4efb-ae22-7b4a2980a96b #之前在nacos中创建的seata的命名空间
group: SEATA_GROUP
username: nacos
password: nacos
- registry:是配置注册中心相关字段,将seata服务作为一个微服务注册到注册中心。将registry.type改成nacos
- type:nacos, eureka, redis, zk, consul, etcd3, sofa,本文使用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: 86ab3ca5-81db-4efb-ae22-7b4a2980a96b
cluster: default
username: nacos
password: nacos
- store:配置seata的存储。将registry.mode改成db
- type:file 、 db 、 redis,本文使用db
store:
# support: file 、 db 、 redis
mode: db
db:
datasource: druid
db-type: mysql
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://192.168.200.139:3306/sxxc_seata?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
user: root
password: root
min-conn: 10
max-conn: 100
global-table: global_table
branch-table: branch_table
lock-table: lock_table
distributed-lock-table: distributed_lock
query-limit: 1000
max-wait: 5000
上面的store:mode使用的是db,这里用mysql8,在数据库中创建sxxc_seata数据库,执行seata-server-1.6.0\seata\script\server\db目录下的mysql.sql文件创建表。全局事务会话由:全局事务、分支事务、全局锁,对应表分别为global_table、branch_table、lock_table。
2.2、config.txt配置
修改\seata\script\config-center下的config.txt文件
#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.default_tx_group=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=file
store.lock.mode=file
store.session.mode=file
#Used for password encryption
store.publicKey=
#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
#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://192.168.200.139:3306/sxxc_seata?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
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.sentinel.masterName=
store.redis.sentinel.sentinelHosts=
store.redis.maxConn=10
store.redis.minConn=1
store.redis.maxTotal=100
store.redis.database=0
store.redis.password=
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
如上配置,修改store.db相关配置。
注意:service.vgroupMapping.default_tx_group=default,这行配置很重要,具体下面解释。
2.3、上传配置至Nacos配置中心
进入\seata\script\config-center\nacos目录,找到nacos-config.sh
在此文件夹下进入终端,执行一下命令
sh nacos-config.sh -h 127.0.0.1 -p 8848 -g SEATA_GROUP -t xxxx -u username -w password
参数详解:
- h nacos服务IP
- p nacos服务端口
- u nacos登录名
- w nacos登录密码
- g nacos 配置的分组名称,默认设置SEATA_GROUP
- t 上面配置的命名空间ID
执行后终端输出:
Set server.maxCommitRetryTimeout=-1 successfully
Set server.maxRollbackRetryTimeout=-1 successfully
Set server.rollbackRetryTimeoutUnlockEnable=false successfully
Set server.distributedLockExpireTime=10000 successfully
Set server.xaerNotaRetryTimeout=60000 successfully
Set server.session.branchAsyncQueueSize=5000 successfully
Set server.session.enableBranchAsyncRemove=false successfully
Set server.enableParallelRequestHandle=false successfully
Set metrics.enabled=false successfully
Set metrics.registryType=compact successfully
Set metrics.exporterList=prometheus successfully
Set metrics.exporterPrometheusPort=9898 successfully
.......
再去nacos控制台查看配置:
进入\seata\bin目录,执行seata-server.bat文件,启动seata。
系统启动成功,再登录 http://127.0.0.1:7091,就能看到seata控制台信息。
nacos控制台服务列表新增了一个服务,说明seata服务成功注册到了nacos注册中心:
3、客户端配置
其他微服务需要使用seata的分布式事务,需要增加配置。
3.1、引入依赖
<!--seata分布式事务管理-->
<dependency>
<groupId>io.seata</groupId>
<artifactId>seata-spring-boot-starter</artifactId>
<version>1.5.2</version>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-seata</artifactId>
<exclusions>
<exclusion>
<groupId>io.seata</groupId>
<artifactId>seata-spring-boot-starter</artifactId>
</exclusion>
</exclusions>
</dependency>
3.2、yml配置
spring:
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
alibaba:
seata:
tx-service-group: ${spring.application.name}-group
application:
name: gulimall-order
server:
port: 9000
# seata配置
seata:
enabled: true
# Seata 应用编号,默认为 ${spring.application.name}
application-id: ${spring.application.name}
# Seata 事务组编号,用于 TC 集群名
tx-service-group: ${spring.application.name}-group
# 开启自动代理
enable-auto-data-source-proxy: true
# 服务配置项
service:
# 虚拟组和分组的映射
vgroup-mapping:
gulimall-order-group: default
config:
type: nacos
nacos:
serverAddr: 127.0.0.1:8848
group: SEATA_GROUP
namespace: 86ab3ca5-81db-4efb-ae22-7b4a2980a96b
registry:
type: nacos
nacos:
application: seata-server
server-addr: 127.0.0.1:8848
namespace: 86ab3ca5-81db-4efb-ae22-7b4a2980a96b
注意:
- 每个微服务都要配置自己应用名的group
- spring:alibaba:seata:tx-service-group: ${spring.application.name}-group
- seata:service:vgroup-mapping:gulimall-order-group: default
同时在nacos的配置中心中新建配置项:
该配置项的data id和spring:alibaba:seata:tx-service-group的值保持一致
- seata:enable-auto-data-source-proxy: true
- 如果该微服务没有自己配置数据源,需要开启数据源代理。
3.3、使用
在需要使用分布式事务的方法上,使用@GlobalTransactional分布式注解,各服务被调用方法使用@Transactional本地事务注解。