seata 分布式事務的環境搭建與使用


一、seata介紹

1. 什么是 seata

seata 是一個分布式事務的解決方案,具有高性能和易用性的微服務架構。其前身是fescar。
seata給用戶提供了AT、TCC、XA和SAGA事務模型。
版本已經更新到了1.4.1,本文采用1.4.0版本進行搭建和測試。
在這里插入圖片描述
文獻資料:http://seata.io
github地址:https://github.com/seata/seata/

2. seata 的基本原理

首先我們先看一張分布式環境下,服務與服務之間的調用關系圖:
在這里插入圖片描述
其實分布式事務是由一批分支事務組成的全局事務,通常分支事務只是本地事務。
在這里插入圖片描述
seata的核心主要有三部分組成:

  • 事務協調器(TC):維護全局事務和分支事務的狀態,驅動全局事務提交或者回滾。
  • 事務管理器(TM):定義全局事務的范圍:開啟全局事務,提交或回滾全局事務(在分布式環境中相當於事務的發起方)。
  • 資源管理器(RM):管理分支事務正在處理的資源,與TC進行對話以注冊分支事務並報告分支事務的狀態。並驅動分支事務的提交或者回滾(在分布式環境中相當於事務的參與者)。
    在這里插入圖片描述
    seata管理的分布式事務的生命周期:
  • 首先,需要構建一個全局事務的協調者TC。
  • 發起方與參與方與全局事務協調者TC建立長連接。
  • 發起方向全局事務協調者申請一個全局事務XID,緩存在本地線程中。
  • 當發起方調用參與方的服務接口時,會將申請到的全局事務XID放入請求頭中。
  • 參與方從請求頭中獲取XID,如果獲取成功,則會向全局事務協調者注冊(為參與方),緩存XID到本地線程。執行完成之后提交本地事務,插入undo_log日志(后期用於回滾使用)。
  • 調用完成參與方服務接口,如果整個業務流程沒有異常,則會通知全局事務協調者,全局事務協調者通知所有的參與方提交事務。事務提交成功后,刪除undo_log日志。
  • 調用完成參與方服務接口,如果整個業務流程存在異常,則會通知全局事務協調者,全局事務協調者通知所有的參與方回滾事務。事務回滾時候,刪除undo_log日志。
    在這里插入圖片描述

二、seata 環境搭建

seata環境搭建會使用到mysql及nacos環境。具體搭建步驟可參照之前發布的文章,如有不詳細的地方,請指正。

1. 服務器端環境搭建

下載seata1.4.0:https://github.com/seata/seata/releases
下載完成后解壓,找到seata\conf\README.md文件,從下方獲取相應的客戶端配置及服務端信息配置
在這里插入圖片描述

  • [client] 主要是客戶端配置,undo_log日志等。
  • [server] 服務端部署腳本,比如使用db存儲模式的時候,會從這里獲取建表語句。
    在這里插入圖片描述
  • [config-center] 存儲配置中心的初始化腳本,將使用配置.txt作為初始配置
    在這里插入圖片描述

1.1 數據庫及表的創建

創建seata數據庫,創建以下表

-- -------------------------------- The script used when storeMode is 'db' --------------------------------
-- the table to store GlobalSession data
CREATE TABLE IF NOT EXISTS `global_table`
(
    `xid`                       VARCHAR(128) NOT NULL,
    `transaction_id`            BIGINT,
    `status`                    TINYINT      NOT NULL,
    `application_id`            VARCHAR(32),
    `transaction_service_group` VARCHAR(32),
    `transaction_name`          VARCHAR(128),
    `timeout`                   INT,
    `begin_time`                BIGINT,
    `application_data`          VARCHAR(2000),
    `gmt_create`                DATETIME,
    `gmt_modified`              DATETIME,
    PRIMARY KEY (`xid`),
    KEY `idx_gmt_modified_status` (`gmt_modified`, `status`),
    KEY `idx_transaction_id` (`transaction_id`)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8;

-- the table to store BranchSession data
CREATE TABLE IF NOT EXISTS `branch_table`
(
    `branch_id`         BIGINT       NOT NULL,
    `xid`               VARCHAR(128) NOT NULL,
    `transaction_id`    BIGINT,
    `resource_group_id` VARCHAR(32),
    `resource_id`       VARCHAR(256),
    `branch_type`       VARCHAR(8),
    `status`            TINYINT,
    `client_id`         VARCHAR(64),
    `application_data`  VARCHAR(2000),
    `gmt_create`        DATETIME(6),
    `gmt_modified`      DATETIME(6),
    PRIMARY KEY (`branch_id`),
    KEY `idx_xid` (`xid`)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8;

-- the table to store lock data
CREATE TABLE IF NOT EXISTS `lock_table`
(
    `row_key`        VARCHAR(128) NOT NULL,
    `xid`            VARCHAR(128),
    `transaction_id` BIGINT,
    `branch_id`      BIGINT       NOT NULL,
    `resource_id`    VARCHAR(256),
    `table_name`     VARCHAR(32),
    `pk`             VARCHAR(36),
    `gmt_create`     DATETIME,
    `gmt_modified`   DATETIME,
    PRIMARY KEY (`row_key`),
    KEY `idx_branch_id` (`branch_id`)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8;

在每一個數據庫中創建undo_log表

-- for AT mode you must to init this sql for you business database. the seata server not need it.
CREATE TABLE IF NOT EXISTS `undo_log`
(
    `branch_id`     BIGINT       NOT NULL COMMENT 'branch transaction id',
    `xid`           VARCHAR(128) NOT NULL COMMENT 'global transaction id',
    `context`       VARCHAR(128) NOT NULL COMMENT 'undo_log context,such as serialization',
    `rollback_info` LONGBLOB     NOT NULL COMMENT 'rollback info',
    `log_status`    INT(11)      NOT NULL COMMENT '0:normal status,1:defense status',
    `log_created`   DATETIME(6)  NOT NULL COMMENT 'create datetime',
    `log_modified`  DATETIME(6)  NOT NULL COMMENT 'modify datetime',
    UNIQUE KEY `ux_undo_log` (`xid`, `branch_id`)
) ENGINE = InnoDB
  AUTO_INCREMENT = 1
  DEFAULT CHARSET = utf8 COMMENT ='AT transaction mode undo table';

創建業務庫user及表sys_user

CREATE TABLE `sys_user` (
  `id` int(11) NOT NULL,
  `user_name` varchar(32) DEFAULT NULL,
  `post` varchar(32) DEFAULT NULL,
  `is_delete` char(2) DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

創建業務庫member及表sys_member

CREATE TABLE `sys_member` (
  `id` int(11) NOT NULL,
  `member_name` varchar(32) DEFAULT NULL,
  `integral` decimal(11,0) DEFAULT NULL,
  `is_delete` char(2) DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

1.2 修改服務器端配置文件

修改seata\conf\file.conf文件
在這里插入圖片描述

修改seata\conf\registry.conf文件

修改注冊類型為nacos

在這里插入圖片描述

修改配置中心為nacos

在這里插入圖片描述
上述配置說明:

nacos.serverAddr:注冊中心/配置中心地址
nacos.namespace:命名空間,如果不填寫默認為public
nacos.gorup:組
nacos.username:nacos用戶名
nacos.password:nacos密碼

1.3 同步config.txt文件到nacos配置中心

將nacos-config.sh(下載地址: [config-center] ) copy到seata\conf\目錄下
在這里插入圖片描述
將config.txt(下載地址: [config-center])copy到seata\目錄下
copy到seata目錄下的原因是能夠使nacos-config.sh腳本讀取到
在這里插入圖片描述
修改config.txt文件,主要修改的幾個位置:

## 事務組,之后在客戶端配置時,要和這個一樣
service.vgroupMapping.my_test_tx_group=default
## seata服務器地址
service.default.grouplist=192.168.0.130:8091 

##與 服務器端中file.conf中相同
store.mode=db 
store.db.datasource=druid
store.db.dbType=mysql
store.db.driverClassName=com.mysql.jdbc.Driver
store.db.url=jdbc:mysql://192.168.137.128:3306/seata?useUnicode=true&rewriteBatchedStatements=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

執行創建命令。在gitbash中執行

sh nacos-config.sh -h 192.168.0.241 -p 8848 -g SEATA_GROUP -t 839c4f2a-612d-417a-9a7d-a4c60fc6bc33 -u nacos -w nacos

創建成功之后,在nacos的配置為:
在這里插入圖片描述

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
service.vgroupMapping.my_test_tx_group=default
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.tm.commitRetryCount=5
client.tm.rollbackRetryCount=5
client.tm.defaultGlobalTransactionTimeout=60000
client.tm.degradeCheck=false
client.tm.degradeCheckAllowTimes=10
client.tm.degradeCheckPeriod=2000
store.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.jdbc.Driver
store.db.url=jdbc:mysql://127.0.0.1:3306/seata?useUnicode=true&rewriteBatchedStatements=true
store.db.user=username
store.db.password=password
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.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
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

2. 客戶端環境搭建

創建兩個項目分別為springboot-user和springboot-member。下方配置引入為共有的,兩個項目中都要引入。沒有貼出代碼配置為項目中私有的代碼,會在文章末尾給出下載地址。

2.1 引入pom依賴

<dependency>
   <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-seata</artifactId>
    <version>2.2.0.RELEASE</version>
    <exclusions>
        <exclusion>
            <groupId>io.seata</groupId>
            <artifactId>seata-spring-boot-starter</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>io.seata</groupId>
    <artifactId>seata-spring-boot-starter</artifactId>
    <version>1.4.0</version>
</dependency>

2.2 在application.yml文件中配置seata信息

seata:
    enabled: true
    enable-auto-data-source-proxy: true #代理數據源
    tx-service-group: my_test_tx_group #要與config.txt中的一致
    registry:
        type: nacos #注冊類型
        nacos:
            application: seata-server
            server-addr: 192.168.0.241:8848
            username: nacos
            password: nacos
            namespace: 839c4f2a-612d-417a-9a7d-a4c60fc6bc33
    config:
        type: nacos # 配置中心類型
        nacos:
            server-addr: 192.168.0.241:8848
            group: SEATA_GROUP
            username: nacos
            password: nacos
            namespace: 839c4f2a-612d-417a-9a7d-a4c60fc6bc33
    service:
        vgroup-mapping:
            my_test_tx_group: default # 默認值,如果在使用事務注解時不指定,采用該默認值
        disable-global-transaction: false
    client:
        rm:
            report-success-enable: false

2.3 代理數據源配置

package com.lee.config;

/**
 * @author zfl_a
 * @date 2021/4/5
 * @project springboot_user
 */

import com.alibaba.druid.pool.DruidDataSource;
import io.seata.rm.datasource.DataSourceProxy;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;

@Configuration
public class DataSourceConfig {

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DruidDataSource druidDataSource() {
        // 或者使用其他數據源
        return new DruidDataSource();
    }

    @Primary
    @Bean
    public DataSource dataSource(DruidDataSource druidDataSource) {
        return new DataSourceProxy(druidDataSource);
    }
}

三、簡單測試

使用@GlobalTransactional注解,斷點打在調用積分成功之后
在這里插入圖片描述
這時查看數據庫是否插入成功
member表
在這里插入圖片描述
undo_log表
在這里插入圖片描述
放行之后發起方報錯,會向全局事務協調者匯報當前狀態,全局事務協調者通知參與方回滾事務
在這里插入圖片描述
回滾之后,member表數據清空了
在這里插入圖片描述
同樣undo_log表也清空了
在這里插入圖片描述

項目地址:https://gitee.com/enthusiasts/springboot-seata.git


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM