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

相关推荐
懒洋洋的华3695 小时前
消息队列-Kafka(概念篇)
分布式·中间件·kafka
March€5 小时前
分布式事务的基本实现
分布式
拾光师6 小时前
spring获取当前request
java·后端·spring
xujinwei_gingko6 小时前
Spring IOC容器Bean对象管理-Java Config方式
java·spring
DieSnowK7 小时前
[Redis][环境配置]详细讲解
数据库·redis·分布式·缓存·环境配置·新手向·详细讲解
Lill_bin8 小时前
深入理解ElasticSearch集群:架构、高可用性与数据一致性
大数据·分布式·elasticsearch·搜索引擎·zookeeper·架构·全文检索
Xua30558 小时前
浅谈Spring Cloud:认识微服务
spring·spring cloud·微服务
JOJO___10 小时前
Spring IoC 配置类 总结
java·后端·spring·java-ee
蜜桃小阿雯11 小时前
JAVA开源项目 校园美食分享平台 计算机毕业设计
java·jvm·spring boot·spring cloud·intellij-idea·美食
黄昏_11 小时前
苍穹外卖Day01-2
java·spring