天天看点

一个小demo迅速掌握分布式事务框架seata的基本使用时

,兄弟们,开卷了~

一个小demo迅速掌握分布式事务框架seata的基本使用时

文章目录

  • ​​一、seata的简介​​
  • ​​1、从单一架构到分布式架构的发展历程​​
  • ​​2、分布式架构出现了什么问题?​​
  • ​​二、模拟分布式场景​​
  • ​​2.1、seata下载安装​​
  • ​​2.2、Nacos+Sentinel的相关教程(打波广告~)​​
  • ​​三、seata的数据表导入​​
  • ​​四、seata-server配置文件的修改​​
  • ​​4.1、修改file.conf​​
  • ​​4.2、修改register.conf​​
  • ​​4.3、将conf.txt上传至nacos​​
  • ​​五、代码准备​​
  • ​​1.模拟思路​​
  • ​​2、核心代码讲解​​
  • ​​3、相关注意点​​
  • ​​六、不使用@GlobalTransactional注解​​
  • ​​七、使用@GlobalTransactional注解​​
代码地址​

一、seata的简介

Seata 是一款开源的分布式事务解决方案,致力于提供高性能和简单易用的分布式事务服务。Seata 将为用户提供了 AT、TCC、SAGA 和 XA 事务模式,为用户打造一站式的分布式解决方案。

1、从单一架构到分布式架构的发展历程

阶段一:最初的互联网由于用户体量小,单一架构就能够满足企业需求。随着互联网的不断发展,用户体量不断增加,普通的单一架构已经不能支撑起庞大的用户量。

阶段二:、数据服务器和应用服务器分离,并发展出了集群的概念

阶段三:在这个阶段人们发现了一种问题,那就是数据库读操作远远大于写操作,这造成了读写比例失衡,对服务器的性能有很大的影响,所以就出现了数据库的读写分离

阶段四: 数据库做读库的话,常常对模糊查询的性能不是很好,所以又引入了搜索引擎这个概念。同时出现了缓存数据库,对热点数据进行存储,减少了数据库的压力。

阶段五: 随着业务的发展,业务越来越多,应用的压力越来越大。服务开始拆分,通过RPC技术进行远程调用

2、分布式架构出现了什么问题?

服务之间的拆分,分库分表到底会产生什么影响。且先看下图

一个小demo迅速掌握分布式事务框架seata的基本使用时

根据上方这张图,你能够看出什么问题;

比如说系统执行到第三步出现了问题,那么前两步已经对商品库存进行了减量,是不是就是出现了很大的问题。

这就是我们常见的事务问题,我们必须要求要么全部成功,要么全部失败!

二、模拟分布式场景

下面我模拟这样一个场景,看看是否会出现这样的问题

2.1、seata下载安装

下载地址:​​https://github.com/seata/seata/releases​​
一个小demo迅速掌握分布式事务框架seata的基本使用时
一个小demo迅速掌握分布式事务框架seata的基本使用时

启动命令就在bin里,一会还需要对配置文件做修改,安装之后先不做任何操作

三、seata的数据表导入

一个小demo迅速掌握分布式事务框架seata的基本使用时
一个小demo迅速掌握分布式事务框架seata的基本使用时
一个小demo迅速掌握分布式事务框架seata的基本使用时
一个小demo迅速掌握分布式事务框架seata的基本使用时
一个小demo迅速掌握分布式事务框架seata的基本使用时

四、seata-server配置文件的修改

4.1、修改file.conf

store mode: file、db、redis
  mode = "db"    //注意修改为db(数据库)
  ## rsa decryption public key
  publicKey = ""
  ## file store property
  file {
    ## store location dir
    dir = "sessionStore"
    # branch session size , if exceeded first try compress lockkey, still exceeded throws exceptions
    maxBranchSessionSize = 16384
    # globe session size , if exceeded throws exceptions
    maxGlobalSessionSize = 512
    # file buffer size , if exceeded allocate new buffer
    fileWriteBufferCacheSize = 16384
    # when recover batch read size
    sessionReloadReadSize = 100
    # async, sync
    flushDiskMode = async
  }

  ## database store property
  db {  //前面修改为db,就会走这条路线
    ## 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"  //注意修改相关mysql连接信息
    driverClassName = "com.mysql.cj.jdbc.Driver"
    ## if using mysql to store the data, recommend add rewriteBatchedStatements=true in jdbc connection param
    url = "jdbc:mysql://rm-b9v16dc34x1uo.mysql.rds.aliyuncs.com:3306/seata?rewriteBatchedStatements=true&serverTimezone=UTC"
    user = "administrator"
    password = "xxxxxxxx"
    minConn = 5
    maxConn = 100
    globalTable = "global_table"
    branchTable = "branch_table"
    lockTable = "lock_table"
    queryLimit = 100
    maxWait = 5000
  }

  ## redis store property
  redis {
    ## redis mode: single、sentinel
    mode = "single"
    ## single mode property
    single {
      host = "127.0.0.1"
      port = "6379"
    }
    ## sentinel mode property
    sentinel {
      masterName = ""
      ## such as "10.28.235.65:26379,10.28.235.65:26380,10.28.235.65:26381"
      sentinelHosts = ""
    }
    password = ""
    database = "0"
    minConn = 1
    maxConn = 10
    maxTotal = 100
    queryLimit = 100
  }
}      

4.2、修改register.conf

registry {
  # file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
  type = "nacos"  //注册中心修改为nacos

  nacos {  //上面是nacos,这里就会走这条nacos路线
    application = "seata-server"
    serverAddr = "124.xx.xxx.xxx:8848"//注册中心地址
    group = "SEATA_GROUP"
    namespace = ""
    cluster = "default"
    username = "nacos"
    password = "nacos"
  }
  eureka {
    serviceUrl = "http://localhost:8761/eureka"
    application = "default"
    weight = "1"
  }
  redis {
    serverAddr = "localhost:6379"
    db = 0
    password = ""
    cluster = "default"
    timeout = 0
  }
  zk {
    cluster = "default"
    serverAddr = "127.0.0.1:2181"
    sessionTimeout = 6000
    connectTimeout = 2000
    username = ""
    password = ""
  }
  consul {
    cluster = "default"
    serverAddr = "127.0.0.1:8500"
    aclToken = ""
  }
  etcd3 {
    cluster = "default"
    serverAddr = "http://localhost:2379"
  }
  sofa {
    serverAddr = "127.0.0.1:9603"
    application = "default"
    region = "DEFAULT_ZONE"
    datacenter = "DefaultDataCenter"
    cluster = "default"
    group = "SEATA_GROUP"
    addressWaitTime = "3000"
  }
  file {
    name = "file.conf"
  }
}

config {
  # file、nacos 、apollo、zk、consul、etcd3
  type = "nacos"  //配置中心修改为nacos

  nacos {    //走这条路线
    serverAddr = "124.xx.xxx.xx:8848"
    namespace = "seata"
    group = "SEATA_GROUP"
    username = "nacos"
    password = "nacos"
    dataId = "seataServer.properties"
  }
  consul {
    serverAddr = "127.0.0.1:8500"
    aclToken = ""
  }
  apollo {
    appId = "seata-server"
    ## apolloConfigService will cover apolloMeta
    apolloMeta = "http://192.168.1.204:8801"
    apolloConfigService = "http://192.168.1.204:8080"
    namespace = "application"
    apolloAccesskeySecret = ""
    cluster = "seata"
  }
  zk {
    serverAddr = "127.0.0.1:2181"
    sessionTimeout = 6000
    connectTimeout = 2000
    username = ""
    password = ""
    nodePath = "/seata/seata.properties"
  }
  etcd3 {
    serverAddr = "http://localhost:2379"
  }
  file {
    name = "file.conf"
  }
}      

4.3、将conf.txt上传至nacos

transport.type=TCP
transport.server=NIO
transport.heartbeat=true
transport.enableClientBatchSendRequest=true
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
service.vgroupMapping.my_test_tx_group=default//这个my_test_tx_group和application.yml对应
service.default.grouplist=127.0.0.1:8091
service.enableDegrade=false
service.disableGlobalTransaction=false
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=false
client.rm.tableMetaCheckerInterval=60000
client.rm.sqlParserType=druid
client.rm.reportSuccessEnable=false
client.rm.sagaBranchRegisterEnable=false
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
store.mode=db    //注意修改为db
store.lock.mode=file
store.session.mode=file
store.publicKey=
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
store.db.datasource=druid
store.db.dbType=mysql    //注意修改相关配置文件
store.db.driverClassName=com.mysql.cj.jdbc.Driver
store.db.url=jdbc:mysql://rm-bp13rrs9v16dc34x1uo.mysql.rds.xxxncs.com:3306/seata_order?serverTimezone=UTC
store.db.user=common_1
store.db.password=Hao_7886
store.db.minConn=5
store.db.maxConn=30
store.db.globalTable=global_table
store.db.branchTable=branch_table
store.db.queryLimit=100
store.db.lockTable=lock_table
store.db.maxWait=5000
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
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
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
log.exceptionRate=100
transport.serialization=seata
transport.compressor=none
metrics.enabled=false
metrics.registryType=compact
metrics.exporterList=prometheus
metrics.exporterPrometheusPort=9898      
nacos-config.sh脚本下载地址:​​https://gitee.com/yuemei/vxx/blob/master/nacos-config.sh​​
一个小demo迅速掌握分布式事务框架seata的基本使用时

将config.txt上传至conf的同级目录,并新建script文件夹,将nacos-config.sh脚本放进去

一个小demo迅速掌握分布式事务框架seata的基本使用时
如果你是自己创建的脚本,然后把脚本代码复制过去的,注意修改脚本文件格式,因为window和Linux脚本格式有点区别。如若不改动,应该会报bash/r错误。

执行nacos-config.sh脚本即可,然后去nacos控制台查看列表

一个小demo迅速掌握分布式事务框架seata的基本使用时

出现这些就代表成功了!

五、代码准备

1.模拟思路

一个小demo迅速掌握分布式事务框架seata的基本使用时

seata组件中的@GlobalTransactional注解能够保证分布式事务的一致性

相关代码我已经上传至CSDN了:​​javascript:void(0)​​

2、核心代码讲解

一个小demo迅速掌握分布式事务框架seata的基本使用时
三个子模块,基本上相关配置是一模一样的

以订单服务模块为例(seata-order-service)

一个小demo迅速掌握分布式事务框架seata的基本使用时
一个小demo迅速掌握分布式事务框架seata的基本使用时
一个小demo迅速掌握分布式事务框架seata的基本使用时
一个小demo迅速掌握分布式事务框架seata的基本使用时
一个小demo迅速掌握分布式事务框架seata的基本使用时

3、相关注意点

1、启动seata-server之前一定要先启动nacos

2、在1.x版本之后,已经改为了驼峰命名(vgroup_mapping->vgroupMapping)

一个小demo迅速掌握分布式事务框架seata的基本使用时

3、启动服务之前,需要将nacos和seata服务启动

4、苍天保佑吧!

六、不使用@GlobalTransactional注解

我在订单状态修改之前,手动加入一个错误,让其结束执行
一个小demo迅速掌握分布式事务框架seata的基本使用时

我设置的订单状态1代表已下单,0代表还未下单(也就是付钱)

一个小demo迅速掌握分布式事务框架seata的基本使用时

未执行之前数据库各表中的数据如下所示

一个小demo迅速掌握分布式事务框架seata的基本使用时
一个小demo迅速掌握分布式事务框架seata的基本使用时
一个小demo迅速掌握分布式事务框架seata的基本使用时

启动服务测试

访问:http://localhost:7071/order/create&userId=1&storageId=1&commodityCode=法拉第&orderCount=1&money=100&status=0

查看控制台

一个小demo迅速掌握分布式事务框架seata的基本使用时

查看数据库表中的数据变化

一个小demo迅速掌握分布式事务框架seata的基本使用时
一个小demo迅速掌握分布式事务框架seata的基本使用时
一个小demo迅速掌握分布式事务框架seata的基本使用时

订单状态未修改(0代表未下单),但是库存和账户余额已经减量了;这就是分布式事务问题,有些成功了,有些失败了,没有做到协调一致

七、使用@GlobalTransactional注解

将数据库中的数据回归到最初

一个小demo迅速掌握分布式事务框架seata的基本使用时
一个小demo迅速掌握分布式事务框架seata的基本使用时
一个小demo迅速掌握分布式事务框架seata的基本使用时

加入@GlobalTransactional注解

一个小demo迅速掌握分布式事务框架seata的基本使用时

重新启动测试,查看控制台

一个小demo迅速掌握分布式事务框架seata的基本使用时

查看数据库表发现没有发送任何变化

一个小demo迅速掌握分布式事务框架seata的基本使用时
一个小demo迅速掌握分布式事务框架seata的基本使用时
一个小demo迅速掌握分布式事务框架seata的基本使用时

此时也可以从undo_log表中查看到记录

以seata_account数据库中的为例
一个小demo迅速掌握分布式事务框架seata的基本使用时

继续阅读