分布式事务管理 Seata

文章目录

1、概述

①、分布式事务问题

分布式前

  • 单机单库,即一个web服务仅对应一个MySQL数据库
  • 1:N​或者N:N,也就是一个服务对应多个数据库或多个服务对应多个数据库。

分布式后

  • 单体应用被拆分成微服务应用,原来的三个模块被拆分成三个独立的应用,分别使用三个独立的数据源,业务操作需要调用三个服务来完成。此时每个服务内部的数据—致性由本地事务来保证,但是全局的数据一致性问题没法保证

分布式事务管理 Seata

②、什么是Seata

官方中文档

SeataSimple Extensible Autonomous Transaction Architecture)是一款开源的分布式事务解决方案,致力于在微服务架构下提供高性能和简单易用的分布式事务服务,能处理一个典型的分布式事务过程

③、Seata术语

分布式事务处理过程的ID+三组件模型

  • Transaction ID全局唯一的事务ID
  • 三组件概念
    • TC (Transaction Coordinator) - 事务协调者:维护全局和分支事务的状态,驱动全局事务提交或回滚。
    • TM (Transaction Manager) - 事务管理器:定义全局事务的范围:开始全局事务、提交或回滚全局事务。
    • RM (Resource Manager) - 资源管理器:管理分支事务处理的资源,与TC交谈以注册分支事务和报告分支事务的状态,并驱动分支事务提交或回滚。

官方示意图

分布式事务管理 Seata

  • TMTC申请开启一个全局事务,全局事务创建成功并生成一个全局唯一的XID
  • XID在微服务调用链路的上下文中传播;
  • RMTC注册分支事务,将其纳入XID对应全局事务的管辖
  • TMTC发起针对XID的全局提交或回滚决议;
  • TC调度XID下管辖的全部分支事务完成提交或回滚请求。

翻译成人话就是

  • 三个Microservices表示三个宿舍,每个宿舍设定8个人,合在一起表示我们班的大家伙(班里人够少的啊)。TC表示我们班的JAVA授课老师伟哥,TM表示我们那万年不理人的辅导员现在辅导员要我们的伟哥开一个班,讲授SpringCloud,伟哥毫不犹豫的就答应了,由于疫情期间,学生都在家,所以就在网课平台开了一个IDXID的直播房间(每次上课都重新创建,房间号都不一样)
  • 由于每个宿舍都有一个QQ群,现在辅导员需要通知所有同学加入课程(也就是原图中所表示的一次事务所涉及到的所有服务),辅导员便在各个宿舍的QQ群发送通知,让同学们根据房间号加入进来,
  • 当同学们都进入直播间以后,老师是可以在房间成员列表看到这些同学的,老师确认对应的同学在线后,便会在心里将这个同学记下来,当要点名回答问题的时候,可以抽他。
  • 这时候辅导员确认同学们都到了以后,就通知伟哥开始上课。
  • 上课结束以后,伟哥通知大家下课休息,可以退出直播间了。

④、怎么用

Seata单说使用,并不复杂,对于如下的分布式交易解决方案

分布式事务管理 Seata

我们只需要使用一个 @GlobalTransactional 注解在业务方法上,加了这个注解的方法就是我们的事务请求发起方,也就是TM,白话也是不理人的辅导员

@GlobalTransactional
public void purchase(String userId, String commodityCode, int orderCount) {
    ......
}

⑤、Windows安装

版本发行说明

下载地址

秉着新版都是留给大佬踩bug的心态,我们稳坐第二排,Git仓库找到一个带有GA标识的稳定版本,然后下载。

分布式事务管理 Seata

Git仓库和官网都有下载链接,都在source资源目录下

分布式事务管理 Seata

下载完成后,解压到本地,进入conf目录,将file.conf文件复制备份一份

分布式事务管理 Seata

编辑该文件,文件中的中文注释自行删除,否则运行可能会报错,这里是给大家说明

分布式事务管理 Seata

既然配置了本地的数据库,就创建所需要的数据库

分布式事务管理 Seata

创建了数据库,还需要建三张表,建表语句如果conf下面没有(部分版本没有,比如我这个1.0),可以上官网找,我这里找到一份,直接复制到navicat中执行

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;

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;

CREATE TABLE IF NOT EXISTS `lock_table`
(
    `row_key`        VARCHAR(128) NOT NULL,
    `xid`            VARCHAR(96),
    `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;

分布式事务管理 Seata

然后回到conf文件夹将registry.conf复制备份一份,再次编辑

分布式事务管理 Seata

然后启动bin目录下的seata-server.bat(前提是你的nacos已经启动成功),启动如果闪退,就以管理员模式启动

分布式事务管理 Seata

然后进入nacos控制台查看服务是否开启

分布式事务管理 Seata

分布式事务管理 Seata

⑥、Docker安装

Ⅰ、MySQL

docker pull mysql:5.7

分布式事务管理 Seata

进入开启容器

docker run -p 33306:3306 --name mysql5.7 -e MYSQL_ROOT_PASSWORD=123456 -d mysql:5.7

连接navicat

分布式事务管理 Seata

开始配置数据库

#进入mysql容器
docker exec -it mysql5.7 /bin/bash
#进入mysql
mysql -uroot -p
#创建seata数据库
create database seata character set utf8;
use seata;
#创建Seate所需要的表
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;

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;

CREATE TABLE IF NOT EXISTS `lock_table`
(
    `row_key`        VARCHAR(128) NOT NULL,
    `xid`            VARCHAR(96),
    `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;
  
#退出容器
exit

接下来创建nacos持久化所需要的nacos_config表,这里演示直接执行sql文件创建数据库,先把nacosconf目录下的nacos-mysql.sql文件上传到服务器,然后在mysql中执行

#这里我没有用数据卷映射宿主机路径了,直接就根据复制到默认的映射文件夹中,其中的id为mysql容器的id,这个怎么查不用教吧
docker cp /opt/nacos-mysql.sql 17c3f76e61f4:/home
#创建nacos数据库
create database nacos character set utf8;
use nacos;
#执行sql文件
source /home/nacos-mysql.sql

分布式事务管理 Seata

分布式事务管理 Seata

Ⅱ、nacos

docker pull nacos/nacos-server

指定数据库MySQL启动nacos(这样就不用进入nacos容器对配置文件一行行进行修改,具体参数需要修改为你自己对于的参数)

docker run --env MODE=standalone --name nacos_seata -d -p 8848:8848 -e MYSQL_SERVICE_HOST=39.105.43.3  -e MYSQL_SERVICE_PORT=33306  -e MYSQL_SERVICE_DB_NAME=nacos  -e MYSQL_SERVICE_USER=root  -e MYSQL_SERVICE_PASSWORD=123456  -e SPRING_DATASOURCE_PLATFORM=mysql  -e MYSQL_DATABASE_NUM=1 nacos/nacos-server

分布式事务管理 Seata

随意增加两条配置,查看数据库是否正常持久化(貌似两条记录的时间和我本机的时间不一样,可能容器里面没同步,暂时不管,应该不影响)

分布式事务管理 Seata

Ⅲ、seata

#拉取镜像
docker pull seataio/seata-server

分布式事务管理 Seata

#运行
docker run --name seata -d -h 39.105.43.3 -p 8091:8091 seataio/seata-server
#进入容器,由于这个镜像是由alpine制作的,执行的是sh而不是bash
docker exec -it seata /bin/sh
#切换目录
cd resource
#备份两个配置文件
cp file.conf file.conf.bk
cp registry.conf registry.conf.bk
#修改file.conf,由于没有vim工具,就用vi编辑了
vi file.conf

分布式事务管理 Seata

url:url = "jdbc:mysql://127.0.0.1:33306/seata?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT%2B8"
#修改registry.conf文件

分布式事务管理 Seata

最后一次重新启动mysqlnacosseata,阿里云莫名1G连三个容器都开不起来了,本文案例演示仍然在windows平台进行,图个方便,有空去虚拟机搞一下

2、配置官网案例

①、分析业务逻辑

回顾业务逻辑

用户购买商品的业务逻辑。整个业务逻辑由3个微服务提供支持:

  • 仓储服务:对于给定的商品扣除仓储数量。
  • 订单服务:根据采购需求创建订单。
  • 账户服务:从用户账户中扣除余额。

这里我们会创建三个服务,一个订单服务,一个库存服务,一个账户服务。

当用户下单时,会在订单服务中创建一个订单,然后通过远程调用库存服务来扣减下单商品的库存,再通过远程调用账户服务来扣减用户账户里面的余额,最

后在订单服务中修改订单状态为已完成。该操作跨越三个数据库,有两次远程调用,很明显会有分布式事务问题。

也就是下订单=》减库存=》减余额

②、创建数据库

CREATE DATABASE seata_order;
CREATE DATABASE seata_storage;
CREATE DATABASE seata_account;

分布式事务管理 Seata

seata_order

CREATE TABLE t_order(
    `id` BIGINT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
    `user_id` BIGINT(11) DEFAULT NULL COMMENT '用户id',
    `product_id` BIGINT(11) DEFAULT NULL COMMENT '产品id',
    `count` BIGINT(11) DEFAULT NULL COMMENT '数量',
    `money` BIGINT(11) DEFAULT NULL COMMENT '金额',
    `status` BIGINT(11) DEFAULT NULL COMMENT '订单状态: 0创建中 1已完结'
) ENGINE = INNODB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;

seata_storage

CREATE TABLE t_storage(
    `id` BIGINT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
    `product_id` BIGINT(11) DEFAULT NULL COMMENT '产品id',
    `total` BIGINT(11) DEFAULT NULL COMMENT '总库存',
    `used` BIGINT(11) DEFAULT NULL COMMENT '已用库存',
    `residue` BIGINT(11) DEFAULT NULL COMMENT '剩余库存'
) ENGINE = INNODB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
 
INSERT INTO t_storage( `id`,`product_id`, `total`,`used`,`residue`) values(1,1,100,0,100);
SELECT * FROM t_storage;

seata_account

CREATE TABLE t_account(
    `id` BIGINT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
    `user_id` BIGINT(11) DEFAULT NULL COMMENT '用户id',
    `total` BIGINT(11) DEFAULT NULL COMMENT '总额度',
    `used` BIGINT(11) DEFAULT NULL COMMENT '已用额度',
    `residue` BIGINT(11) DEFAULT NULL COMMENT '剩余额度'
) ENGINE = INNODB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
 
INSERT INTO t_account( `id`,`user_id`, `total`,`used`,`residue`) values(1,1,1000,0,1000);
SELECT * FROM t_account;

分布式事务管理 Seata

找到conf目录下的db_undo_log.sql文件,拷贝其中的sql语句执行(1.0的又没有),有没有都无所谓了,我直接贴出来,在三个数据库中分别执行以下语句,创建日志回滚表

CREATE TABLE `undo_log` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `branch_id` bigint(20) NOT NULL,
  `xid` varchar(100) NOT NULL,
  `context` varchar(128) NOT NULL,
  `rollback_info` longblob NOT NULL,
  `log_status` int(11) NOT NULL,
  `log_created` datetime NOT NULL,
  `log_modified` datetime NOT NULL,
  `ext` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `ux_undo_log` (`xid`,`branch_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

③、订单模块

Ⅰ、建Module

分布式事务管理 Seata

Ⅱ、POM

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>SpringCloudDemo</artifactId>
        <groupId>com.phz.springcloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>SeataConsumerOrder2001</artifactId>

    <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>
                    <groupId>io.seata</groupId>
                    <artifactId>seata-all</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!--上面派出了自带的seata,然后引入我们本地版本的1.0-->
        <dependency>
            <groupId>io.seata</groupId>
            <artifactId>seata-all</artifactId>
            <version>1.0.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!--jdbc-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--hutool 测试雪花算法-->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-captcha</artifactId>
            <version>5.2.0</version>
        </dependency>
    </dependencies>
</project>

Ⅲ、YML

server:
  port: 2001

spring:
  application:
    name: seata-order-service
  cloud:
    alibaba:
      seata:
        # 自定义事务组名称需要与seata-server中的对应
        tx-service-group: phz_test
    nacos:
      discovery:
        server-addr: 39.105.43.3:8848
  datasource:
    # 当前数据源操作类型
    type: com.alibaba.druid.pool.DruidDataSource
    # mysql驱动类
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql:///seata_order?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT%2B8
    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
  #thread factory for netty
  thread-factory {
    boss-thread-prefix = "NettyBoss"
    worker-thread-prefix = "NettyServerNIOWorker"
    server-executor-thread-prefix = "NettyServerBizHandler"
    share-boss-worker = false
    client-selector-thread-prefix = "NettyClientSelector"
    client-selector-thread-size = 1
    client-worker-thread-prefix = "NettyClientWorkerThread"
    # netty boss thread size,will not be used for UDT
    boss-thread-size = 1
    #auto default pin or 8
    worker-thread-size = 8
  }
  shutdown {
    # when destroy server, wait seconds
    wait = 3
  }
  serialization = "seata"
  compressor = "none"
}
service {
  #vgroup->rgroup
  # 事务组名称
  vgroup_mapping.fsp_tx_group = "default"
  #only support single node
  default.grouplist = "127.0.0.1:8091"
  #degrade current not support
  enableDegrade = false
  #disable
  disable = false
  #unit ms,s,m,h,d represents milliseconds, seconds, minutes, hours, days, default permanent
  max.commit.retry.timeout = "-1"
  max.rollback.retry.timeout = "-1"
  disableGlobalTransaction = false
}

client {
  async.commit.buffer.limit = 10000
  lock {
    retry.internal = 10
    retry.times = 30
  }
  report.retry.count = 5
  tm.commit.retry.count = 1
  tm.rollback.retry.count = 1
}

## transaction log store
store {
  ## store mode: file、db
  #mode = "file"
  mode = "db"

  ## file store
  file {
    dir = "sessionStore"

    # branch session size , if exceeded first try compress lockkey, still exceeded throws exceptions
    max-branch-session-size = 16384
    # globe session size , if exceeded throws exceptions
    max-global-session-size = 512
    # file buffer size , if exceeded allocate new buffer
    file-write-buffer-cache-size = 16384
    # when recover batch read size
    session.reload.read_size = 100
    # async, sync
    flush-disk-mode = async
  }

  ## database store
  db {
    ## the implement of javax.sql.DataSource, such as DruidDataSource(druid)/BasicDataSource(dbcp) etc.
    datasource = "dbcp"
    ## mysql/oracle/h2/oceanbase etc.
    db-type = "mysql"
    driver-class-name = "com.mysql.jdbc.Driver"
    url = "jdbc:mysql://127.0.0.1:3306/seata"
    user = "root"
    password = "123456"
    min-conn = 1
    max-conn = 3
    global.table = "global_table"
    branch.table = "branch_table"
    lock-table = "lock_table"
    query-limit = 100
  }
}
lock {
  ## the lock store mode: local、remote
  mode = "remote"

  local {
    ## store locks in user's database
  }

  remote {
    ## store locks in the seata's server
  }
}
recovery {
  #schedule committing retry period in milliseconds
  committing-retry-period = 1000
  #schedule asyn committing retry period in milliseconds
  asyn-committing-retry-period = 1000
  #schedule rollbacking retry period in milliseconds
  rollbacking-retry-period = 1000
  #schedule timeout retry period in milliseconds
  timeout-retry-period = 1000
}

transaction {
  undo.data.validation = true
  undo.log.serialization = "jackson"
  undo.log.save.days = 7
  #schedule delete expired undo_log in milliseconds
  undo.log.delete.period = 86400000
  undo.log.table = "undo_log"
}

## metrics settings
metrics {
  enabled = false
  registry-type = "compact"
  # multi exporters use comma divided
  exporter-list = "prometheus"
  exporter-prometheus-port = 9898
}

support {
  ## spring
  spring {
    # auto proxy the DataSource bean
    datasource.autoproxy = false
  }
}

Ⅴ、registry.conf

registry {
  # file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
  type = "nacos"

  nacos {
    #serverAddr = "localhost"
    serverAddr = "39.105.43.3:8848"
    namespace = ""
    cluster = "default"
  }
  eureka {
    serviceUrl = "http://localhost:8761/eureka"
    application = "default"
    weight = "1"
  }
  redis {
    serverAddr = "localhost:6379"
    db = "0"
  }
  zk {
    cluster = "default"
    serverAddr = "127.0.0.1:2181"
    session.timeout = 6000
    connect.timeout = 2000
  }
  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
  type = "file"

  nacos {
    serverAddr = "localhost"
    namespace = ""
  }
  consul {
    serverAddr = "127.0.0.1:8500"
  }
  apollo {
    app.id = "seata-server"
    apollo.meta = "http://192.168.1.204:8801"
  }
  zk {
    serverAddr = "127.0.0.1:2181"
    session.timeout = 6000
    connect.timeout = 2000
  }
  etcd3 {
    serverAddr = "http://localhost:2379"
  }
  file {
    name = "file.conf"
  }
}

Ⅵ、业务类

domain

/**
 * @author PengHuAnZhi
 * @createTime 2021/2/25 16:52
 * @projectName SpringCloudDemo
 * @className Order.java
 * @description TODO
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Order {

    private Long id;

    private Long userId;

    private Long productId;

    private Integer count;

    private BigDecimal money;

    private Integer status; // 订单状态 0:创建中 1:已完结
}

/**
 * @author PengHuAnZhi
 * @createTime 2021/2/25 16:51
 * @projectName SpringCloudDemo
 * @className CommonResult.java
 * @description TODO
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class CommonResult<T> {
    private Integer code;
    private String message;
    private T data;

    public CommonResult(Integer code, String message) {
        this(code, message, null);
    }
}

dao

/**
 * @author PengHuAnZhi
 * @createTime 2021/2/25 16:55
 * @projectName SpringCloudDemo
 * @className OrderDao.java
 * @description TODO
 */
@Mapper
public interface OrderDao {
    /**
     * 1 新建订单
     *
     * @param order
     * @return
     */
    int create(Order order);

    /**
     * 2 修改订单状态,从0改为1
     *
     * @param userId
     * @param status
     * @return
     */
    int update(@Param("userId") Long userId, @Param("status") Integer status);
}

mapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.phz.dao.OrderDao">

    <resultMap id="BaseResultMap" type="com.phz.domain.Order">
        <id column="id" property="id" jdbcType="BIGINT"></id>
        <result column="user_id" property="userId" jdbcType="BIGINT"></result>
        <result column="product_id" property="productId" jdbcType="BIGINT"></result>
        <result column="count" property="count" jdbcType="INTEGER"></result>
        <result column="money" property="money" jdbcType="DECIMAL"></result>
        <result column="status" property="status" jdbcType="INTEGER"></result>
    </resultMap>

    <insert id="create" parameterType="com.phz.domain.Order" useGeneratedKeys="true"
            keyProperty="id">
        insert into t_order(user_id,product_id,count,money,status) values (#{userId},#{productId},#{count},#{money},0);
    </insert>

    <update id="update">
        update t_order set status =1 where user_id =#{userId} and status=#{status};
    </update>
</mapper>

service

/**
 * @author PengHuAnZhi
 * @createTime 2021/2/25 17:01
 * @projectName SpringCloudDemo
 * @className StorageService.java
 * @description TODO
 */
@FeignClient(value = "seata-storage-service")
public interface StorageService {

    /**
     * 减库存
     * @param productId
     * @param count
     * @return
     */
    @PostMapping(value = "/storage/decrease")
    CommonResult decrease(@RequestParam("productId") Long productId, @RequestParam("count") Integer count);
}

/**
 * @author PengHuAnZhi
 * @createTime 2021/2/25 17:01
 * @projectName SpringCloudDemo
 * @className OrderService.java
 * @description TODO
 */
public interface OrderService {

    /**
     * 创建订单
     * @param order
     */
    void create(Order order);
}

/**
 * @author PengHuAnZhi
 * @createTime 2021/2/25 17:01
 * @projectName SpringCloudDemo
 * @className AccountService.java
 * @description TODO
 */
@FeignClient(value = "seata-account-service")
public interface AccountService {

    /**
     * 减余额
     * @param userId
     * @param money
     * @return
     */
    @PostMapping(value = "/account/decrease")
    CommonResult decrease(@RequestParam("userId") Long userId, @RequestParam("money") BigDecimal money);
}

impl

/**
 * @author PengHuAnZhi
 * @createTime 2021/2/25 17:03
 * @projectName SpringCloudDemo
 * @className OrderServiceImpl.java
 * @description TODO
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Resource
    private OrderDao orderDao;
    @Resource
    private AccountService accountService;
    @Resource
    private StorageService storageService;

    /**
     * 创建订单->调用库存服务扣减库存->调用账户服务扣减账户余额->修改订单状态
     * 简单说:
     * 下订单->减库存->减余额->改状态
     * GlobalTransactional seata开启分布式事务,异常时回滚,name保证唯一即可
     *
     * @param order 订单对象
     */
    @Override
    ///@GlobalTransactional(name = "fsp-create-order", rollbackFor = Exception.class)
    public void create(Order order) {
        // 1 新建订单
        log.info("----->开始新建订单");
        orderDao.create(order);

        // 2 扣减库存
        log.info("----->订单微服务开始调用库存,做扣减Count");
        storageService.decrease(order.getProductId(), order.getCount());
        log.info("----->订单微服务开始调用库存,做扣减End");

        // 3 扣减账户
        log.info("----->订单微服务开始调用账户,做扣减Money");
        accountService.decrease(order.getUserId(), order.getMoney());
        log.info("----->订单微服务开始调用账户,做扣减End");

        // 4 修改订单状态,从0到1,1代表已完成
        log.info("----->修改订单状态开始");
        orderDao.update(order.getUserId(), 0);

        log.info("----->下订单结束了,O(∩_∩)O哈哈~");
    }
}

controller

/**
 * @author PengHuAnZhi
 * @createTime 2021/2/25 17:08
 * @projectName SpringCloudDemo
 * @className OrderController.java
 * @description TODO
 */
@RestController
public class OrderController {
    @Resource
    private OrderService orderService;


    /**
     * 创建订单
     *
     * @param order
     * @return
     */
    @GetMapping("/order/create")
    public CommonResult create(Order order) {
        orderService.create(order);
        return new CommonResult(200, "订单创建成功");
    }
}

config

/**
 * @author PengHuAnZhi
 * @createTime 2021/2/25 17:10
 * @projectName SpringCloudDemo
 * @className DataSourceProxyConfig.java
 * @description TODO
 */
@Configuration
public class DataSourceProxyConfig {

    @Value("${mybatis.mapperLocations}")
    private String mapperLocations;

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource druidDataSource() {
        return new DruidDataSource();
    }

    @Bean
    public DataSourceProxy dataSourceProxy(DataSource druidDataSource) {
        return new DataSourceProxy(druidDataSource);
    }

    @Bean
    public SqlSessionFactory sqlSessionFactoryBean(DataSourceProxy dataSourceProxy) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSourceProxy);
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        bean.setMapperLocations(resolver.getResources(mapperLocations));
        return bean.getObject();
    }
}

/**
 * @author PengHuAnZhi
 * @createTime 2021/2/25 17:08
 * @projectName SpringCloudDemo
 * @className MybatisConfig.java
 * @description TODO
 */
@Configuration
@MapperScan({"com.phz.dao"})
public class MybatisConfig {

}

Ⅶ、主启动

/**
 * @author PengHuAnZhi
 * @createTime 2021/2/25 17:12
 * @projectName SpringCloudDemo
 * @className SeataOrderMain2001.java
 * @description TODO
 */
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class) //取消数据源的自动创建
@EnableDiscoveryClient
@EnableFeignClients
public class SeataOrderMain2001 {
    public static void main(String[] args) {
        SpringApplication.run(SeataOrderMain2001.class, args);
    }
}

④、库存模块

Ⅰ、Module

分布式事务管理 Seata

Ⅱ、POM

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>SpringCloudDemo</artifactId>
        <groupId>com.phz.springcloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>SeataStorageService2002</artifactId>

    <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>
                    <groupId>io.seata</groupId>
                    <artifactId>seata-all</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>io.seata</groupId>
            <artifactId>seata-all</artifactId>
            <version>1.0.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!--jdbc-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <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>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

Ⅲ、YML

server:
  port: 2002

spring:
  application:
    name: seata-storage-service
  cloud:
    alibaba:
      seata:
        # 自定义事务组名称需要与seata-server中的对应
        tx-service-group: phz_test
    nacos:
      discovery:
        server-addr: 39.105.43.3:8848
  datasource:
    # 当前数据源操作类型
    type: com.alibaba.druid.pool.DruidDataSource
    # mysql驱动类
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql:///seata_storage?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT%2B8
    username: root
    password: 123456
feign:
  hystrix:
    enabled: false
logging:
  level:
    io:
      seata: info

mybatis:
  mapperLocations: classpath*:mapper/*.xml

Ⅳ、file.conf

#参考2001,一样

Ⅴ、registry.conf

#参考2001,一样

Ⅵ、业务类

domain

/**
 * @author PengHuAnZhi
 * @createTime 2021/2/25 17:36
 * @projectName SpringCloudDemo
 * @className Storage.java
 * @description TODO
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Storage {

    private Long id;

    private Long productId;

    private Integer total;

    private Integer used;

    private Integer residue;
}

//还有一个CommonResult复制2001即可

dao

/**
 * @author PengHuAnZhi
 * @createTime 2021/2/25 17:36
 * @projectName SpringCloudDemo
 * @className StorageDao.java
 * @description TODO
 */
@Mapper
public interface StorageDao {

    void decrease(@Param("productId") Long productId, @Param("count") Integer count);

}

mapper

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.phz.dao.StorageDao">

    <resultMap id="BaseResultMap" type="com.phz.domain.Storage">
        <id column="id" property="id" jdbcType="BIGINT"/>
        <result column="product_id" property="productId" jdbcType="BIGINT"/>
        <result column="total" property="total" jdbcType="INTEGER"/>
        <result column="used" property="used" jdbcType="INTEGER"/>
        <result column="residue" property="residue" jdbcType="INTEGER"/>
    </resultMap>

    <update id="decrease">
        update t_storage
        set used = used + #{count}, residue = residue - #{count}
        where product_id= #{productId};
    </update>
</mapper>

service

/**
 * @author PengHuAnZhi
 * @createTime 2021/2/25 17:38
 * @projectName SpringCloudDemo
 * @className StorageService.java
 * @description TODO
 */
public interface StorageService {
    void decrease(@RequestParam("productId") Long productId, @RequestParam("count") Integer count);
}

impl

/**
 * @author PengHuAnZhi
 * @createTime 2021/2/25 17:40
 * @projectName SpringCloudDemo
 * @className StorageServiceImpl.java
 * @description TODO
 */
@Service
@Slf4j
public class StorageServiceImpl implements StorageService {

    @Resource
    private StorageDao storageDao;
    @Override
    public void decrease(Long productId, Integer count) {
        log.info("----> StorageService中扣减库存");
        storageDao.decrease(productId, count);
        log.info("----> StorageService中扣减库存完成");
    }
}

controller

/**
 * @author PengHuAnZhi
 * @createTime 2021/2/25 17:41
 * @projectName SpringCloudDemo
 * @className StorageController.java
 * @description TODO
 */
@RestController
@Slf4j
public class StorageController {

    @Resource
    private StorageService storageService;

    @RequestMapping("/storage/decrease")
    public CommonResult decrease(@RequestParam("productId") Long productId, @RequestParam("count") Integer count){
        storageService.decrease(productId, count);
        log.info("扣减库存成功!");
        return new CommonResult(200, "扣减库存成功!");
    }
}

config

/**
 * @author PengHuAnZhi
 * @createTime 2021/2/25 17:46
 * @projectName SpringCloudDemo
 * @className MybatisConfig.java
 * @description TODO
 */
@Configuration
@MapperScan({"com.phz.dao"})
public class MybatisConfig {
}

/**
 * @author PengHuAnZhi
 * @createTime 2021/2/25 17:47
 * @projectName SpringCloudDemo
 * @className DataSourceProxyConfig.java
 * @description TODO
 */
@Configuration
public class DataSourceProxyConfig {

    @Value("${mybatis.mapperLocations}")
    private String mapperLocations;

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource druidDataSource() {
        return new DruidDataSource();
    }

    @Bean
    public DataSourceProxy dataSourceProxy(DataSource druidDataSource) {
        return new DataSourceProxy(druidDataSource);
    }

    @Bean
    public SqlSessionFactory sqlSessionFactoryBean(DataSourceProxy dataSourceProxy) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSourceProxy);
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        bean.setMapperLocations(resolver.getResources(mapperLocations));
        return bean.getObject();
    }
}

Ⅶ、主启动

/**
 * @author PengHuAnZhi
 * @createTime 2021/2/25 17:47
 * @projectName SpringCloudDemo
 * @className SeataStorageMain2002.java
 * @description TODO
 */
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
@EnableFeignClients
@EnableDiscoveryClient
public class SeataStorageMain2002 {

    public static void main(String[] args) {
        SpringApplication.run(SeataStorageMain2002.class, args);
    }
}

⑤、支付模块

Ⅰ、Module

分布式事务管理 Seata

Ⅱ、POM

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>SpringCloudDemo</artifactId>
        <groupId>com.phz.springcloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>SeataAccountService2003</artifactId>

    <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>
                    <groupId>io.seata</groupId>
                    <artifactId>seata-all</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>io.seata</groupId>
            <artifactId>seata-all</artifactId>
            <version>1.0.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!--jdbc-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <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>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

Ⅲ、YML

server:
  port: 2003

spring:
  application:
    name: seata-account-service
  cloud:
    alibaba:
      seata:
        # 自定义事务组名称需要与seata-server中的对应
        tx-service-group: phz_test
    nacos:
      discovery:
        server-addr: 39.105.43.3:8848
  datasource:
    # 当前数据源操作类型
    type: com.alibaba.druid.pool.DruidDataSource
    # mysql驱动类
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql:///seata_account?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT%2B8
    username: root
    password: 123456
feign:
  hystrix:
    enabled: false
logging:
  level:
    io:
      seata: info

mybatis:
  mapperLocations: classpath*:mapper/*.xml

Ⅳ、file.conf

#参考2001,一样

Ⅴ、registry.conf

#参考2001,一样

Ⅵ、业务类

domain

/**
 * @author PengHuAnZhi
 * @createTime 2021/2/25 17:51
 * @projectName SpringCloudDemo
 * @className Account.java
 * @description TODO
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Account {

    private Long id;

    private Long userId;

    private BigDecimal total;

    private BigDecimal used;

    private BigDecimal  residue;
}

//还有一个CommonResult复制2001即可

dao

/**
 * @author PengHuAnZhi
 * @createTime 2021/2/25 17:51
 * @projectName SpringCloudDemo
 * @className AccountDao.java
 * @description TODO
 */
@Mapper
public interface AccountDao {

    void decrease(@Param("userId") Long userId, @Param("money") BigDecimal money);

}

mapper

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.phz.dao.AccountDao">

    <resultMap id="BaseResultMap" type="com.phz.domain.Account">
        <id column="id" property="id" jdbcType="BIGINT"/>
        <result column="user_id" property="userId" jdbcType="BIGINT"/>
        <result column="total" property="total" jdbcType="DECIMAL"/>
        <result column="used" property="used" jdbcType="DECIMAL"/>
        <result column="residue" property="residue" jdbcType="DECIMAL"/>
    </resultMap>

    <update id="decrease">
        update t_account
        set used = used + #{money}, residue = residue - #{money}
        where user_id = #{userId};
    </update>
</mapper>

service

/**
 * @author PengHuAnZhi
 * @createTime 2021/2/25 17:53
 * @projectName SpringCloudDemo
 * @className AccountService.java
 * @description TODO
 */
public interface AccountService {
    void decrease(Long userId, BigDecimal money);
}

impl

/**
 * @author PengHuAnZhi
 * @createTime 2021/2/25 17:54
 * @projectName SpringCloudDemo
 * @className AccountServiceImpl.java
 * @description TODO
 */
@Service
@Slf4j
public class AccountServiceImpl implements AccountService {

    @Resource
    private AccountDao accountDao;

    @Override
    public void decrease(Long userId, BigDecimal money) {
        log.info("---> AccountService中扣减账户余额");
        accountDao.decrease(userId, money);
        log.info("---> AccountService中扣减账户余额完成");
    }
}

controller

/**
 * @author PengHuAnZhi
 * @createTime 2021/2/25 17:55
 * @projectName SpringCloudDemo
 * @className AccountController.java
 * @description TODO
 */
@RestController
public class AccountController {

    @Resource
    private AccountService accountService;

    @RequestMapping("/account/decrease")
    public CommonResult decrease(@RequestParam("userId") Long userId, @RequestParam("money") BigDecimal money){
        accountService.decrease(userId, money);
        return new CommonResult(200, "扣减库存成功!");
    }

}

config

/**
 * @author PengHuAnZhi
 * @createTime 2021/2/25 17:46
 * @projectName SpringCloudDemo
 * @className MybatisConfig.java
 * @description TODO
 */
@Configuration
@MapperScan({"com.phz.dao"})
public class MybatisConfig {
}

/**
 * @author PengHuAnZhi
 * @createTime 2021/2/25 17:47
 * @projectName SpringCloudDemo
 * @className DataSourceProxyConfig.java
 * @description TODO
 */
@Configuration
public class DataSourceProxyConfig {

    @Value("${mybatis.mapperLocations}")
    private String mapperLocations;

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource druidDataSource() {
        return new DruidDataSource();
    }

    @Bean
    public DataSourceProxy dataSourceProxy(DataSource druidDataSource) {
        return new DataSourceProxy(druidDataSource);
    }

    @Bean
    public SqlSessionFactory sqlSessionFactoryBean(DataSourceProxy dataSourceProxy) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSourceProxy);
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        bean.setMapperLocations(resolver.getResources(mapperLocations));
        return bean.getObject();
    }
}

Ⅶ、主启动

/**
 * @author PengHuAnZhi
 * @createTime 2021/2/25 17:56
 * @projectName SpringCloudDemo
 * @className SeataAccountMain2003.java
 * @description TODO
 */
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
@EnableFeignClients
@EnableDiscoveryClient
public class SeataAccountMain2003 {

    public static void main(String[] args) {
        SpringApplication.run(SeataAccountMain2003.class,args);
    }
}

⑥、测试

Ⅰ、一般情况

发送下单请求(我直接发了十条全买完了。。)

http://localhost:2001/order/create?userId=1&productId=1&count=10&money=100

分布式事务管理 Seata

查看数据库是否正常

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-wYBHqw4I-1614257598021)(C:\Users\PengHuAnZhi\AppData\Roaming\Typora\typora-user-images\image-20210225184721173.png)]

Ⅱ、意外情况

如果支付服务突然失败怎么办?在支付服务Controller中添加一个超时语句

//模拟超时异常,暂停20秒
try {
    TimeUnit.SECONDS.sleep(20);
} catch (InterruptedException e) {
    e.printStackTrace();
}

前面手贱点了十次直接卖完了,所以这次做个弊,直接手动在数据库中修改库存,再加一百个,然后用户余额再加1000

分布式事务管理 Seata

分布式事务管理 Seata

浏览器执行访问(我又点了两下),报错肯定报错,图都不用截了,肯定超时了,重点在观察数据库

http://localhost:2001/order/create?userId=1&productId=1&count=10&money=100

分布式事务管理 Seata

Ⅲ、解决办法

我们只需要使用一个 @GlobalTransactional 注解在业务方法上,也就是2001Controller

/**
  * 创建订单
  *
  * @param order
  * @return
  */
//name随便命名,只要不重复即可
//rollbackFor = Exception.class表示出现所有异常都回滚
//rollbackFor表示哪些需要回滚
//noRollbackFor表示哪些不需要回滚
@GlobalTransactional(name = "fsp-create-order", rollbackFor = Exception.class)
@GetMapping("/order/create")
public CommonResult create(Order order) {
    orderService.create(order);
    return new CommonResult(200, "订单创建成功");
}

重启测试一下

分布式事务管理 Seata

分布式事务管理 Seata

证明配置生效了

3、原理简述

①、是什么

观察官方文档在介绍Seata的时候,提到了若干的事务模式,而我们个人用户默认只用到了AT模式,其他模式好像是收费,这里介绍AT模式

分布式事务管理 Seata

整体机制

两阶段提交协议的演变:

  • 一阶段:业务数据和回滚日志记录在同一个本地事务中提交,释放本地锁和连接资源。
  • 二阶段:
    • 提交异步化,非常快速地完成。
    • 回滚通过一阶段的回滚日志进行反向补偿。

②、一阶段加载

在一阶段,Seata会拦截“业务SQL” :

  • 解析SQL语义,找到“业务SQL”要更新的业务数据,在业务数据被更新前,将其保存成“before images
  • 执行“业务SQL”更新业务数据,在业务数据更新之后,
  • 其保存成“after image”,最后生成行锁。

以上操作全部在一个数据库事务内完成,这样保证了—阶段操作的原子性。

分布式事务管理 Seata

③、二阶段提交

二阶段如是顺利提交的话,

因为“业务SQL”在一阶段已经提交至数据库,所以Seata框架只需将一阶段保存的快照数据和行锁删掉,完成数据清理即可。

分布式事务管理 Seata

④、二阶段回滚

二阶段回滚:

二阶段如果是回滚的话,Seata 就需要回滚一阶段已经执行的“业务SQL”,还原业务数据。

回滚方式便是用“before image”还原业务数据;但在还原前要首先要校验脏写,对比“数据库当前业务数据”和“after image'如果两份数据完全一致就说明没

有脏写,可以还原业务数据,如果不一致就说明有脏写,出现脏写就需要转人工处理。

分布式事务管理 Seata

上一篇:springcloud-alibaba学习笔记(六)docker搭建seata测试环境和(file模式)配置seata-server的地址


下一篇:Seata 分布式事务