Seata處理分布式事務(wù)

1.分布式事務(wù)問題

image.png
image.png

一次業(yè)務(wù)操作需要跨多個(gè)數(shù)據(jù)源或需要跨多個(gè)系統(tǒng)進(jìn)行遠(yuǎn)程調(diào)用,就會(huì)產(chǎn)生分布式事務(wù)問題.

2.Seata簡(jiǎn)介

Seata是一款開源的分布式事務(wù)解決方案,致力于在微服務(wù)架構(gòu)下提供高性能和簡(jiǎn)單易用的分布式事務(wù)服務(wù)
官網(wǎng)地址:http://seata.io/zh-cn/

分布式事務(wù)處理過程的-ID+三組件模型
Transaction ID XID,全局唯一的事務(wù)ID
3組件概念:
Transaction Coordinator(TC)
事務(wù)協(xié)調(diào)器,維護(hù)全局事務(wù)的運(yùn)行狀態(tài),負(fù)責(zé)協(xié)調(diào)并驅(qū)動(dòng)全局事務(wù)的提交或回滾;
Transaction Manager(TM)
控制全局事務(wù)的邊界,負(fù)責(zé)開啟一個(gè)全局事務(wù),并最終發(fā)起全局提交或全局回滾的決議;
Resource Manager(RM)
控制分支事務(wù),負(fù)責(zé)分支注冊(cè),狀態(tài)匯報(bào),并接收事務(wù)協(xié)調(diào)器的指令,驅(qū)動(dòng)分支(本地)事務(wù)的提交和回滾;

處理過程:

image.png
image.png

Spring 本地@Transactional
全局@GlobalTransactional

image.png

3.Seata-Server安裝

下載版本:http://seata.io/zh-cn/ (1.3.0v) 解壓到指定目錄
下載源碼:拷貝server和client,.sql文件到conf目錄,創(chuàng)建seate數(shù)據(jù)庫和表(server)
https://github.com/seata/seata/blob/1.3.0/script/server/db/mysql.sql

3.1SERVER 配置

3.1.1修改conf目錄下registry.conf(先備份原始registry.conf文件)

registry {
  # file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
#配置nacos作為seata-server注冊(cè)中心
  type = "nacos"

  nacos {
    application = "seata-server"
    serverAddr = "192.168.1.111:1111"
    group = "DEV_GROUP"
    namespace = "300c5dc3-6326-4033-8d7e-effe12645735"
    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"
  }
  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
  #配置nacos為配置中心,如果配置file ,啟用file.conf文件
  type = "nacos"

  nacos {
    serverAddr = "192.168.1.111:1111"
    namespace = "300c5dc3-6326-4033-8d7e-effe12645735"
    group = "DEV_GROUP"
    username = "nacos"
    password = "nacos"
  }
  consul {
    serverAddr = "127.0.0.1:8500"
  }
  apollo {
    appId = "seata-server"
    apolloMeta = "http://192.168.1.204:8801"
    namespace = "application"
  }
  zk {
    serverAddr = "127.0.0.1:2181"
    sessionTimeout = 6000
    connectTimeout = 2000
    username = ""
    password = ""
  }
  etcd3 {
    serverAddr = "http://localhost:2379"
  }
  file {
    name = "file.conf"
  }
}

3.1.2registry.conf中配置中心配置file,需要修改conf目錄下的file.conf配置文件(先備份原始file.conf文件)

主要修改:自定義事務(wù)組名稱
## transaction log store, only used in seata-server
store {
  ## store mode: file、db、redis
 #事務(wù)日志存儲(chǔ)模式為db
  mode = "db"

  ## 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 
 #數(shù)據(jù)庫連接信息
  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"
    driverClassName = "com.mysql.jdbc.Driver"
    url = "jdbc:mysql://192.168.1.115:3306/seata"
    user = "root"
    password = "123456"
    minConn = 5
    maxConn = 30
    globalTable = "global_table"
    branchTable = "branch_table"
    lockTable = "lock_table"
    queryLimit = 100
    maxWait = 5000
  }

  ## redis store property
  redis {
    host = "127.0.0.1"
    port = "6379"
    password = ""
    database = "0"
    minConn = 1
    maxConn = 10
    queryLimit = 100
  }
}

3.1.3registry.conf中配置中心配置nacos
上傳配置至Nacos配置中心
參考https://github.com/seata/seata/tree/develop/script/config-center 的config.txt, 拷貝config.txt和nacos-config.sh到seata-server,
修改config.txt

transport.type=TCP
transport.server=NIO
transport.heartbeat=true
transport.enableClientBatchSendRequest=false
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
#修改fsp-tx-group事務(wù)組名稱為default,
#fsp-tx-group和微服務(wù)配置一致spring.cloud.alibaba.seata.tx-service-group=fsp-tx-group
#注意高版本vgroupMapping
service.vgroupMapping.fsp-tx-group=default
service.default.grouplist=192.168.1.114: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.sqlParserType=druid
client.rm.reportSuccessEnable=false
client.rm.sagaBranchRegisterEnable=false
client.tm.commitRetryCount=5
client.tm.rollbackRetryCount=5
client.tm.degradeCheck=false
client.tm.degradeCheckAllowTimes=10
client.tm.degradeCheckPeriod=2000
#配置事務(wù)日志模式db
store.mode=db
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.jdbc.Driver
#配置數(shù)據(jù)源
store.db.url=jdbc:mysql://192.168.1.115:3306/seata?useUnicode=true
store.db.user=root
store.db.password=123456
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.host=127.0.0.1
store.redis.port=6379
store.redis.maxConn=10
store.redis.minConn=1
store.redis.database=0
store.redis.password=null
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
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.log.exceptionRate=100
transport.serialization=seata
transport.compressor=none
metrics.enabled=false
metrics.registryType=compact
metrics.exporterList=prometheus
metrics.exporterPrometheusPort=9898

3.1.4配置信息提交到nacos
運(yùn)行倉庫中提供的nacos腳本./nacos-config.sh,將信息提交到nacos控制臺(tái),如果有需要更改,可直接通過控制臺(tái)更改.

image.png

3.1.5隨后,啟動(dòng) Seata-Server

image.png

您同樣也能發(fā)現(xiàn)Server 和Client部分配置都已經(jīng)從配置中心中讀取,例如:store.mode.

3.2client service配置

3.2.1業(yè)務(wù)數(shù)據(jù)庫準(zhǔn)備
業(yè)務(wù)庫表略..
對(duì)于AT模式,必須為業(yè)務(wù)數(shù)據(jù)庫分別建對(duì)應(yīng)的回滾日志表,初始化此sql。seata服務(wù)器不需要它。
https://github.com/seata/seata/blob/1.3.0/script/client/at/db/mysql.sql

3.2.2業(yè)務(wù)微服務(wù)準(zhǔn)備
POM配置

    <dependencies>
        <!--nacos-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <!--seata-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-seata</artifactId>
            <exclusions>
                <exclusion>
                    <artifactId>seata-all</artifactId>
                    <groupId>io.seata</groupId>
                </exclusion>
            </exclusions>
        </dependency>
      <!--依賴seata-server版本一致-->
        <dependency>
            <groupId>io.seata</groupId>
            <artifactId>seata-all</artifactId>
            <version>1.3.0</version>
        </dependency>
        <!--feign-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
        <!--web-actuator-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <!--mysql-druid-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.37</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>

YML配置

application.yml配置指定命名空間名稱
spring:
  profiles:
    active: dev

bootstrap.yml 配置服務(wù)名和nacos,seata事務(wù)組
server:
  port: 2001

spring:
  application:
    name: seata-order-service
  cloud:
    alibaba:
      seata:
        #自定義事務(wù)組名稱需要與seata-server中的對(duì)應(yīng)
        tx-service-group: fsp-tx-group
#配置nacos服務(wù)注冊(cè)中心和配置中心
    nacos:
      discovery:
        server-addr: 192.168.1.111:1111
        group: DEV_GROUP
        namespace: 300c5dc3-6326-4033-8d7e-effe12645735
      config:
        server-addr: 192.168.1.111:1111 #配置中心地址(nginx)
        file-extension: yaml #指定yaml格式的配置
        group: DEV_GROUP
        namespace: 300c5dc3-6326-4033-8d7e-effe12645735
#業(yè)務(wù)配置可在nacos配置,供服務(wù)讀取
#  datasource:
#    driver-class-name: com.mysql.jdbc.Driver
#    url: jdbc:mysql://192.168.1.115:3306/seata_order
#    username: root
#    password: 123456
#
#feign:
#  hystrix:
#    enabled: false
#
#logging:
#  level:
#    io:
#      seata: info
#
#mybatis:
#  mapperLocations: classpath:mapper/*.xml

file.conf

transport {
  # tcp udt unix-domain-socket
  type = "TCP"
  #NIO NATIVE
  server = "NIO"
  #enable heartbeat
  heartbeat = true
  # the client batch send request enable
  enableClientBatchSendRequest = true
  #thread factory for netty
  threadFactory {
    bossThreadPrefix = "NettyBoss"
    workerThreadPrefix = "NettyServerNIOWorker"
    serverExecutorThread-prefix = "NettyServerBizHandler"
    shareBossWorker = false
    clientSelectorThreadPrefix = "NettyClientSelector"
    clientSelectorThreadSize = 1
    clientWorkerThreadPrefix = "NettyClientWorkerThread"
    # netty boss thread size,will not be used for UDT
    bossThreadSize = 1
    #auto default pin or 8
    workerThreadSize = "default"
  }
  shutdown {
    # when destroy server, wait seconds
    wait = 3
  }
  serialization = "seata"
  compressor = "none"
}
service {
  #transaction service group mapping
  vgroupMapping.fsp-tx-group = "default"
  #only support when registry.type=file, please don't set multiple addresses
  default.grouplist = "127.0.0.1:8091"
  #degrade, current not support
  enableDegrade = false
  #disable seata
  disableGlobalTransaction = false
}

client {
  rm {
    asyncCommitBufferLimit = 10000
    lock {
      retryInterval = 10
      retryTimes = 30
      retryPolicyBranchRollbackOnConflict = true
    }
    reportRetryCount = 5
    tableMetaCheckEnable = false
    reportSuccessEnable = false
    sagaBranchRegisterEnable = false
  }
  tm {
    commitRetryCount = 5
    rollbackRetryCount = 5
    degradeCheck = false
    degradeCheckPeriod = 2000
    degradeCheckAllowTimes = 10
  }
  undo {
    dataValidation = true
    onlyCareUpdateColumns = true
    logSerialization = "jackson"
    logTable = "undo_log"
  }
  log {
    exceptionRate = 100
  }
}

registry.conf

#注冊(cè)中心服務(wù)發(fā)現(xiàn)配置nacos
registry {
  # file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
  type = "nacos"

  nacos {
    application = "seata-server"
    serverAddr = "192.168.1.111:1111"
    group = "DEV_GROUP"
    namespace = "300c5dc3-6326-4033-8d7e-effe12645735"
    username = "nacos"
    password = "nacos"
  }
  eureka {
    serviceUrl = "http://localhost:8761/eureka"
    weight = "1"
  }
  redis {
    serverAddr = "localhost:6379"
    db = "0"
    password = ""
    timeout = "0"
  }
  zk {
    serverAddr = "127.0.0.1:2181"
    sessionTimeout = 6000
    connectTimeout = 2000
    username = ""
    password = ""
  }
  consul {
    serverAddr = "127.0.0.1:8500"
  }
  etcd3 {
    serverAddr = "http://localhost:2379"
  }
  sofa {
    serverAddr = "127.0.0.1:9603"
    region = "DEFAULT_ZONE"
    datacenter = "DefaultDataCenter"
    group = "SEATA_GROUP"
    addressWaitTime = "3000"
  }
  file {
    name = "file.conf"
  }
}
#配置中心使用file ,啟用file.conf; 如果使用nacos 需配置相關(guān)配置
config {
  # file、nacos 、apollo、zk、consul、etcd3、springCloudConfig
  type = "file"

  nacos {
    serverAddr = "192.168.1.111:1111"
    namespace = "300c5dc3-6326-4033-8d7e-effe12645735"
    group = "DEV_GROUP"
    username = "nacos"
    password = "nacos"
  }
  consul {
    serverAddr = "127.0.0.1:8500"
  }
  apollo {
    appId = "seata-server"
    apolloMeta = "http://192.168.1.204:8801"
    namespace = "application"
  }
  zk {
    serverAddr = "127.0.0.1:2181"
    sessionTimeout = 6000
    connectTimeout = 2000
    username = ""
    password = ""
  }
  etcd3 {
    serverAddr = "http://localhost:2379"
  }
  file {
    name = "file.conf"
  }
}

3.2.3業(yè)務(wù)代碼
略...

4.分布式事務(wù)的執(zhí)行流程

image.png

TM開啟分布式事務(wù)(TM向TC注冊(cè)全局事務(wù)記錄)
換業(yè)務(wù)場(chǎng)景,編排數(shù)據(jù)庫,服務(wù)等事務(wù)內(nèi)資源(RM向TC匯報(bào)資源準(zhǔn)備狀態(tài))
TM結(jié)束分布式事務(wù),事務(wù)一階段結(jié)束(TM通知TC提交/回滾分布式事務(wù))
TC匯總事務(wù)信息,決定分布式事務(wù)是提交還是回滾
TC通知所有RM提交/回滾資源,事務(wù)二階段結(jié)束。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容