springcloud接入seata管理分布式事务

下载安装包

链接: seata

配置seata-server

文件上传Linux解压

压缩包我放在/usr/local/seata中

tar -zxvf seata-server-2.0.0.tar.gz

修改配置文件

设置nacos为注册和配置中心

  1. 进入文件夹

    cd /usr/local/seata/seata/conf

  2. 修改application.yml文件

    ......
    ......
    console:
    user:
    username: seata
    password: seata
    seata:
    config:
    # support: nacos, consul, apollo, zk, etcd3
    type: nacos
    nacos:
    server-addr: ip:8848
    group: 'DEFAULT_GROUP'
    namespace: '32e627d0-0b4xxxxxxx'
    dataId: "seataServer.properties"
    username: 'nacos'
    password: 'nacos'
    registry:
    # support: nacos, eureka, redis, zk, consul, etcd3, sofa
    type: nacos
    preferred-networks: xx.xx.*
    nacos:
    application: "seata-server"
    server-addr: ip:8848
    group: 'DEFAULT_GROUP'
    namespace: '32e627d0-0b4xxxxxxx'
    username: 'nacos'
    password: 'nacos'
    ......
    ......

  3. 将seata配置文件上传到nacos

在nacos新建配置文件seataServer.properties

官方供参考的配置文件: 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=db
store.lock.mode=db
store.session.mode=db
#Used for password encryption
# store.publicKey=

#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://ip:3306/seata?useUnicode=true&rewriteBatchedStatements=true
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

#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

创建seata数据库及回滚表

  1. 在mysql新建了一个名为seata的数据库

  2. 导入seata回滚所需的表,链接: 表结构地址。根据自己的数据库选择。

  3. 在需要接入seata的相关微服务数据库中,创建undo_log表。链接:表结构地址,根据自己的数据库选择。(接入服务的数据库不同,都要创建一次)

设置seata自启动

  1. 进入文件夹

    /etc/systemd/system

  2. 创建seata.service文件

    #固定写法,换一下路径即可
    #!/bin/sh
    [Unit]
    Description=seata-service
    After=syslog.target network.target remote-fs.target nss-lookup.target
    [Service]
    Type=forking
    Environment="JAVA_HOME=/usr/local/java/jdk1.8.0_311"
    ExecStart=/usr/local/seata/seata/bin/seata-server.sh -p 8091 -h ip
    PrivateTmp=true
    [Install]
    WantedBy=multi-user.target

【注意】:此处-h 后接当前主机IP,如不接在nacos上注册的,会显示为172开头的虚拟IP

  1. 设置开机自启并刷新配置

    systemctl enable seata
    systemctl daemon-reload # 刷新配置

  2. 启动seata

    systemctl start seata
    systemctl status seata # 查看服务状态

  3. 完成
    打开浏览器ip:7091,即可看到控制台。账号密码为前面修改配置文件设置的密码,即seata。

微服务接入seata

pom中引入seata依赖

<dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-seata</artifactId>
</dependency>

yml配置文件设置

# seata配置
seata:
  enabled: true
  application-id: ${spring.application.name}
  tx-service-group: default_tx_group
  # 关闭自动代理
  enable-auto-data-source-proxy: false
  # seata nacos注册中心配置
  registry:
    type: nacos
    nacos:
      application: seata-server
      server-addr:  nacos的ip:8848
      group: DEFAULT_GROUP
      namespace: 32e627d0-0b49-48de-b298-fb959134e1c5
      username: 'nacos'
      password: 'nacos'
  # seata nacos配置中心配置
  config:
    type: nacos
    nacos:
      server-addr:  nacos的IP:8848
      group: DEFAULT_GROUP
      namespace: 32e627d0-0b49-48de-b298-fb959134e1c5
      data-id: seataServer.properties
      username: 'nacos'
      password: 'nacos'

【注意】:这里需要非常注意的是tx-service-group的值,要和seataServer.properties里面的相同。

#Transaction routing rules configuration, only for the client
service.vgroupMapping.default_tx_group=default

使用

主接口增加注解 @GlobalTransactional,远程调用服务增加注解 @Transactional。项目接入多数据源,新建两方法分别插入数据到不同库,看回滚效果。

TIPS:本项目使用的是mybatis-plus

相关推荐
paopaokaka_luck3 小时前
【360】基于springboot的志愿服务管理系统
java·spring boot·后端·spring·毕业设计
Yaml45 小时前
Spring Boot 与 Vue 共筑二手书籍交易卓越平台
java·spring boot·后端·mysql·spring·vue·二手书籍
P.H. Infinity5 小时前
【RabbitMQ】03-交换机
分布式·rabbitmq
aloha_7896 小时前
从零记录搭建一个干净的mybatis环境
java·笔记·spring·spring cloud·maven·mybatis·springboot
龙哥·三年风水7 小时前
群控系统服务端开发模式-应用开发-个人资料
分布式·php·群控系统
wyh要好好学习8 小时前
SpringMVC快速上手
java·spring
尢词8 小时前
SpringMVC
java·spring·java-ee·tomcat·maven
茶馆大橘8 小时前
微服务系列五:避免雪崩问题的限流、隔离、熔断措施
java·jmeter·spring cloud·微服务·云原生·架构·sentinel
wrx繁星点点8 小时前
享元模式:高效管理共享对象的设计模式
java·开发语言·spring·设计模式·maven·intellij-idea·享元模式
funnyZpC10 小时前
quartz集群增强版🎉
java·分布式·开源·集群·定时任务