有來實驗室|第一篇:Seata1.5.2版本部署和開源全棧商城訂單支付業務實戰

在線體驗:Seata實驗室

一. 前言

相信 youlai-mall 的實驗室大家有曾在項目中見到過,但應該都還處於陌生的階段,畢竟在此之前實驗室多是以概念般的形式存在,所以我想借着此次的機會,對其進行一個詳細的說明。

實驗室模塊的建立初衷和開源項目的成立一致的,都是爲了提升開發成員的技術能力,只不過開源項目是從技術棧廣度上(全棧),而實驗室則是從技術棧深度方面切入,更重要的它是一種更深刻而又高效的學習方式。爲什麼能夠這麼說?因爲實驗室是結合真實的業務場景把中間件的作用可視化出來,達到通過現象去看本質(原理和源碼)的目的,再也不是被動式輸入的短期記憶學習。

實驗室未來計劃是將工作和麪試常見的中間件(Spring、MyBatis、Redis、Seata、MQ、MySQL、ES等)做進來,本篇就以 Seata 爲例正式爲有來實驗室拉開一個序幕。

二. Seata 概念

Seata 是一款開源的分佈式事務解決方案,致力於提供高性能和簡單易用的分佈式事務服務。Seata 將爲用戶提供了 AT、TCC、SAGA 和 XA 事務模式,爲用戶打造一站式的分佈式解決方案。

術語
TC (Transaction Coordinator) - 事務協調者 維護全局和分支事務的狀態,驅動全局事務提交或回滾。
TM (Transaction Manager) - 事務管理器 定義全局事務的範圍:開始全局事務、提交或回滾全局事務。
RM (Resource Manager) - 資源管理器 管理分支事務處理的資源,與TC交談以註冊分支事務和報告分支事務的狀態,並驅動分支事務提交或回滾。

三. Seata 服務端部署

中間件聲明

中間件 版本 服務器IP 端口
Seata 1.5.2 192.168.10.100 8091、7091
Nacos 2.0.3 192.168.10.99 8848
MySQL 8.0.27 192.168.10.98 3306

官方鏈接

名稱 地址
文檔 http://seata.io/zh-cn/
源碼 https://github.com/seata/seata
MySQL腳本 https://github.com/seata/seata/blob/1.5.2/script/server/db/mysql.sql
Seata外置配置 https://github.com/seata/seata/blob/1.5.2/script/config-center/config.txt

Seata 數據庫

Seata 表結構MySQL腳本在線地址: https://github.com/seata/seata/blob/1.5.2/script/server/db/mysql.sql

執行以下腳本完成 Seata 數據庫創建和表的初始化:

-- 1. 執行語句創建名爲 seata 的數據庫
CREATE DATABASE seata DEFAULT CHARACTER SET utf8mb4 DEFAULT COLLATE utf8mb4_general_ci;

-- 2.執行腳本完成 Seata 表結構的創建
use seata;

-- 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_status_gmt_modified` (`status` , `gmt_modified`),
    KEY `idx_transaction_id` (`transaction_id`)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8mb4;

-- 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 = utf8mb4;

-- 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),
    `status`         TINYINT      NOT NULL DEFAULT '0' COMMENT '0:locked ,1:rollbacking',
    `gmt_create`     DATETIME,
    `gmt_modified`   DATETIME,
    PRIMARY KEY (`row_key`),
    KEY `idx_status` (`status`),
    KEY `idx_branch_id` (`branch_id`),
    KEY `idx_xid_and_branch_id` (`xid` , `branch_id`)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8mb4;

CREATE TABLE IF NOT EXISTS `distributed_lock`
(
    `lock_key`       CHAR(20) NOT NULL,
    `lock_value`     VARCHAR(20) NOT NULL,
    `expire`         BIGINT,
    primary key (`lock_key`)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8mb4;

INSERT INTO `distributed_lock` (lock_key, lock_value, expire) VALUES ('AsyncCommitting', ' ', 0);
INSERT INTO `distributed_lock` (lock_key, lock_value, expire) VALUES ('RetryCommitting', ' ', 0);
INSERT INTO `distributed_lock` (lock_key, lock_value, expire) VALUES ('RetryRollbacking', ' ', 0);
INSERT INTO `distributed_lock` (lock_key, lock_value, expire) VALUES ('TxTimeoutCheck', ' ', 0);

Seata 配置

這裏採用 Nacos 作爲配置中心的方式,所以需要把 Seata 的外置配置 放置在Nacos上

1. 獲取 Seata 外置配置

獲取Seata 配置在線地址:https://github.com/seata/seata/blob/1.5.2/script/config-center/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=file
store.lock.mode=file
store.session.mode=file
#Used for password encryption
store.publicKey=

#If `store.mode,store.lock.mode,store.session.mode` are not equal to `file`, you can remove the configuration block.
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

#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.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.distributedLockTable=distributed_lock
store.db.queryLimit=100
store.db.lockTable=lock_table
store.db.maxWait=5000

#These configurations are required if the `store mode` is `redis`. If `store.mode,store.lock.mode,store.session.mode` are not equal to `redis`, you can remove the configuration block.
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

#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

2. 導入配置至 Nacos

在 Nacos 默認的 public 命名空間下 ,新建配置 Data ID 爲 seataServer.properties ,Group 爲 SEATA_GROUP 的配置

image-20221124235041087

image-20221124235347673

3. 修改 Seata 外置配置

把默認 Seata 全量配置導入 Nacos 之後,本篇這裏僅需修存儲模式爲db以及對應的db連接配置

# 修改store.mode爲db,配置數據庫連接
store.mode=db
store.db.dbType=mysql
store.db.driverClassName=com.mysql.cj.jdbc.Driver
store.db.url=jdbc:mysql://192.168.10.98:3306/seata?useUnicode=true&rewriteBatchedStatements=true
store.db.user=root
store.db.password=123456
  • **store.mode=db **存儲模式選擇爲數據庫
  • 192.168.10.98 MySQL主機地址
  • store.db.user=root 數據庫用戶名
  • store.db.password=123456 數據庫密碼

Seata 部署

Seata 官方部署文檔https://seata.io/zh-cn/docs/ops/deploy-by-docker.html

1. 獲取應用配置

按照官方文檔描述使用自定義配置文件的部署方式,需要先創建臨時容器把配置copy到宿主機

創建臨時容器

docker run -d --name seata-server -p 8091:8091 -p 7091:7091 seataio/seata-server:1.5.2

創建掛載目錄

mkdir -p /mnt/seata/config

複製容器配置至宿主機

docker cp seata-server:/seata-server/resources/ /mnt/seata/config

注意複製到宿主機的目錄,下文啓動容器需要做宿主機和容器的目錄掛載

image-20221126122442156

過河拆橋,刪除臨時容器

docker rm -f seata-server

2. 修改啓動配置

在獲取到 seata-server 的應用配置之後,因爲這裏採用 Nacos 作爲 seata 的配置中心和註冊中心,所以需要修改 application.yml 裏的配置中心和註冊中心地址,詳細配置我們可以從 application.example.yml 拿到。

application.yml 原配置

image-20221126103400571

修改後的配置(參考 application.example.yml 示例文件),以下是需要調整的部分,其他配置默認即可

seata:
  config:
    type: nacos
    nacos:
      server-addr: 192.168.10.99:8848
      namespace:
      group: SEATA_GROUP
      data-id: seataServer.properties
  registry:
    type: nacos
    preferred-networks: 30.240.*
    nacos:
      application: seata-server
      server-addr: 192.168.10.99:8848
      namespace:
      group: SEATA_GROUP
      cluster: default
  # 存儲模式在外置配置(Nacos)中,Nacos 配置加載優先級大於application.yml,會被application.yml覆蓋,所以此處註釋
  #store:
  	#mode: file
  • 192.168.10.99 是Nacos宿主機的IP地址,Docker部署別錯填 localhost 或Docker容器的IP(172.17. * . *)
  • namespace nacos命名空間id,不填默認是public命名空間
  • data-id: seataServer.properties Seata外置文件所處Naocs的Data ID,參考上小節的 導入配置至 Nacos
  • group: SEATA_GROUP 指定註冊至nacos註冊中心的分組名
  • cluster: default 指定註冊至nacos註冊中心的集羣名

3. 啓動容器

docker run -d --name seata-server --restart=always  \
-p 8091:8091 \
-p 7091:7091 \
-e SEATA_IP=192.168.10.100 \
-v /mnt/seata/config:/seata-server/resources \
seataio/seata-server:1.5.2 
  • /mnt/seata/config Seata應用配置掛載在宿主機的目錄

  • 192.168.10.100 Seata 宿主機IP地址

在 nacos 控制檯 的 public 命名空間下服務列表裏有 seata-server 說明部署啓動成功

image-20221126123623622

如果啓動失敗或者未註冊到 nacos , 基本是粗心的結果,請仔細檢查下自己 application.yml 的註冊中心配置或查看日誌

 docker logs -f --tail=100 seata-server

以上就完成對 Seata 服務端的部署和配置,接下來就是 SpringBoot 與 Seata 客戶端的整合。

四. Seata 客戶端搭建

1. Maven 依賴

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-seata</artifactId>
    <!-- 默認seata客戶端版本比較低,排除後重新引入指定版本-->
    <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.5.2</version>
</dependency>

2. undo_log 表

undo_log表腳本: https://github.com/seata/seata/blob/1.5.2/script/client/at/db/mysql.sql

-- 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 = utf8mb4 COMMENT ='AT transaction mode undo table';

AT模式兩階段提交協議的演變:

  • 一階段:業務數據和回滾日誌記錄在同一個本地事務中提交,釋放本地鎖和連接資源。
  • 二階段:
    • 提交異步化,非常快速地完成。
    • 回滾通過一階段的回滾日誌進行反向補償。

Seata的AT模式下之所以在第一階段直接提交事務,依賴的是需要在每個RM創建一張undo_log表,記錄業務執行前後的數據快照。

如果二階段需要回滾,直接根據undo_log表回滾,如果執行成功,則在第二階段刪除對應的快照數據。

3. 客戶端配置

# Seata配置
seata:
  enabled: true
  # 指定事務分組至集羣映射關係,集羣名default需要與seata-server註冊到Nacos的cluster保持一致
  service:
    vgroup-mapping:
      mall_tx_group: default 
  # 事務分組配置
  tx-service-group: mall_tx_group
  registry:
    type: nacos
    nacos:
      application: seata-server
      # nacos 服務地址
      server-addr: 192.168.10.99:8848
      namespace:
      group: SEATA_GROUP

以上3點就是 Seata 客戶端需要做的事項,下面就 Seata 如何實戰應用進行展開詳細說明。

五. Seata 實戰

Seata 官網示例: http://seata.io/zh-cn/docs/user/quickstart.html

需求

用戶購買商品訂單支付的業務邏輯。整個業務邏輯由3個微服務提供支持:

  • 商品服務:扣減商品庫存。
  • 訂單服務:修改訂單狀態【已支付】。
  • 會員服務:扣減賬戶餘額。

架構圖

  • TM:事務管理器(有來實驗室:laboratory)
  • RM:資源管理器(商城服務:mall-pms;會員服務:mall-ums;訂單服務:mall-oms)
  • TC :事務協調者(Seata服務端:seata-server)

代碼實現

有來實驗室

實驗室在“訂單支付”案例中扮演的是【事務管理器】的角色,其工作內容是開始全局事務、提交或回滾全局事務。

按照 【第三節-Seata客戶端搭建 】 在 laboratory 模塊添加 Maven 依賴和客戶端的配置。

訂單支付關鍵代碼片段(SeataServiceImpl#payOrderWithGlobalTx),通過註解 GlobalTransactional 開啓全局事務,通過對商品 Feign 客戶端和訂單 Feign 客戶端的調用完成訂單支付的流程,這是全局事務開始的地方。


    /**
     * 訂單支付(全局事務)
     */
    @GlobalTransactional
    public boolean payOrderWithGlobalTx(SeataForm seataForm) {

        log.info("========扣減商品庫存========");
        skuFeignClient.deductStock(skuId, 1); 

        log.info("========訂單支付========");
        orderFeignClient.payOrder(orderId, ...);

        return true;
    }

商品服務

按照 【第三節-Seata客戶端搭建 】 在 mall-pms 模塊添加 Maven 依賴和客戶端的配置,在 mall-pms 數據庫創建 undo_log 表。

扣減庫存關鍵代碼:

    /**
     * 「實驗室」扣減商品庫存
     */
    public boolean deductStock(Long skuId, Integer num) {
        boolean result = this.update(new LambdaUpdateWrapper<PmsSku>()
                .setSql("stock_num = stock_num - " + num)
                .eq(PmsSku::getId, skuId)
        );
        return result;
    }

訂單服務

按照 【第三節-Seata客戶端搭建 】 在 mall-oms 模塊添加 Maven 依賴和客戶端的配置,在 mall-oms 數據庫創建 undo_log 表。

訂單支付關鍵代碼:

    /**
     * 「實驗室」訂單支付
     */
    public Boolean payOrder(Long orderId, SeataOrderDTO orderDTO) {

        Long memberId = orderDTO.getMemberId();
        Long amount = orderDTO.getAmount();

        // 扣減賬戶餘額
        memberFeignClient.deductBalance(memberId, amount);

        // 【關鍵】如果開啓異常,全局事務將會回滾
        Boolean openEx = orderDTO.getOpenEx();
        if (openEx) {
            int i = 1 / 0;
        }

        // 修改訂單【已支付】
        boolean result = this.update(new LambdaUpdateWrapper<OmsOrder>()
                .eq(OmsOrder::getId, orderId)
                .set(OmsOrder::getStatus, OrderStatusEnum.WAIT_SHIPPING.getValue())
        );

        return result;
    }

會員服務

按照 【第三節-Seata客戶端搭建 】 在 mall-ums 模塊添加 Maven 依賴和客戶端的配置,在 mall-ums 數據庫創建 undo_log 表。

扣減餘額關鍵代碼:

    @ApiOperation(value = "「實驗室」扣減會員餘額")
    @PutMapping("/{memberId}/balances/_deduct")
    public Result deductBalance(@PathVariable Long memberId, @RequestParam Long amount) {
        boolean result = memberService.update(new LambdaUpdateWrapper<UmsMember>()
                .setSql("balance = balance - " + amount)
                .eq(UmsMember::getId, memberId));
        return Result.judge(result);
    }

測試

以上就基於 youlai-mall 商城訂單支付的業務簡單實現的 Seata 實驗室,接下來通過測試來看看 Seata 分佈式事務的能力。

未開啓事務

未開啓事務前提: 訂單狀態因爲異常修改失敗,但這並未影響到商品庫存扣減和餘額扣減成功的結果,明顯這不是希望的結果。

image-20221204163239115

開啓事務

開啓事務前提:訂單狀態修改發生異常,同時也回滾了扣減庫存、扣減餘額的行爲,可見 Seata 分佈式事務生效。

image-20221204163205891

六. Seata 源碼

因爲 Seata 源碼牽涉角色比較多,需要在本地搭建 seata-server 然後和 Seata 客戶端交互調試,後面整理出來會單獨拿一篇文章進行進行具體分析。

image-20221204222607903

七. 結語

本篇通過 Seata 1.5.2 版本部署到實戰講述了 Seata 分佈式事務AT模式在商城訂單支付業務場景的應用,相信大家對 Seata 和有來實驗室有個初步的認知,但這裏還只是一個開始,後續會有更多的熱門中間件登上實驗室舞臺。當然,可見這個舞臺很大,所以也希望有興趣或者有想法同學加入有來實驗室的開發。

附. 源碼

本文源碼已推送至gitee和github倉庫

gitee github
後端工程 https://gitee.com/youlaitech/youlai-mall https://github.com/youlaitech/youlai-mall
前端工程 https://gitee.com/youlaiorg/mall-admin https://github.com/youlaitech/mall-admin
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章