分布式事务框架 Seata 入门案例

打印 上一主题 下一主题

主题 523|帖子 523|积分 1569

1.  Seata Server 部署
Seata分TC、TM和RM三个角色,TC(Server端)为单独服务端部署,TM和RM(Client端)由业务系统集成。
首先,下载最新的安装包

也可以下载源码,然后本地编译。最新的版本是1.5.2

下载后的启动包(或者源码)中有个scripts目录,里面有各种我们所需的脚本

Server端存储模式(store.mode)现有file、db、redis三种:

  • file模式为单机模式,全局事务会话信息内存中读写并持久化本地文件root.data,性能较高;(不推荐)
  • db模式为高可用模式,全局事务会话信息通过db共享,相应性能差些;
  • redis模式Seata-Server 1.3及以上版本支持,性能较高,存在事务信息丢失风险,请提前配置合适当前场景的redis持久化配置;
修改配置文件

  • 启动包:seata-->conf-->application.yml
  • 源码包:根目录-->seata-server-->resources-->application.yml
主要修改的点是:

  • 修改store.mode="db或者redis"
  • 修改seata.config、seata.registry
  • 修改数据库连接|redis属性配置
在资源目录还有一个application.example.yml文件,application.example.yml中附带额外配置,可以将其db|redis相关配置复制至application.yml,进行修改store.db或store.redis相关属性。

如果不使用外部配置中心,直接使用本地文件配置的话,那么最简单的配置可能是这样的:
  1. server:
  2.   port: 7091
  3. spring:
  4.   application:
  5.     name: seata-server
  6. logging:
  7.   config: classpath:logback-spring.xml
  8.   file:
  9.     path: ${user.home}/logs/seata
  10.   extend:
  11.     logstash-appender:
  12.       destination: 127.0.0.1:4560
  13.     kafka-appender:
  14.       bootstrap-servers: 127.0.0.1:9092
  15.       topic: logback_to_logstash
  16. console:
  17.   user:
  18.     username: seata
  19.     password: seata
  20. seata:
  21.   config:
  22.     type: file
  23.   registry:
  24.     type: nacos
  25.     nacos:
  26.       application: seata-server
  27.       server-addr: 127.0.0.1:8848
  28.       group: SEATA_GROUP
  29.       namespace:
  30.       cluster: default
  31.   store:
  32.     mode: db
  33.     db:
  34.       datasource: druid
  35.       db-type: mysql
  36.       driver-class-name: com.mysql.cj.jdbc.Driver
  37.       url: jdbc:mysql://127.0.0.1:3306/seata?rewriteBatchedStatements=true&useUnicode=true&serverTimezone=Asia/Shanghai
  38.       user: root
  39.       password: 123456
  40.       min-conn: 5
  41.       max-conn: 100
  42.       global-table: global_table
  43.       branch-table: branch_table
  44.       lock-table: lock_table
  45.       distributed-lock-table: distributed_lock
  46.       query-limit: 100
  47.       max-wait: 5000
  48.   security:
  49.     secretKey: SeataSecretKey0c382ef121d778043159209298fd40bf3850a017
  50.     tokenValidityInMilliseconds: 1800000
  51.     ignore:
  52.       urls: /,/**/*.css,/**/*.js,/**/*.html,/**/*.map,/**/*.svg,/**/*.png,/**/*.ico,/console-fe/public/**,/api/v1/auth/login
复制代码

更多配置请参见 https://seata.io/zh-cn/docs/user/configurations.html
这里面哪些是Server端需要配置的,哪些是Client端需要配置的,以及每个参数的含义都解释得非常详细,强烈建议看一下,这里就不在赘述。
此处注册中心用nacos
https://nacos.io/zh-cn/index.html



建表(默认数据库是seata)
  1. USE `seata`;
  2. -- -------------------------------- The script used when storeMode is 'db' --------------------------------
  3. -- the table to store GlobalSession data
  4. CREATE TABLE IF NOT EXISTS `global_table`
  5. (
  6.     `xid`                       VARCHAR(128) NOT NULL,
  7.     `transaction_id`            BIGINT,
  8.     `status`                    TINYINT      NOT NULL,
  9.     `application_id`            VARCHAR(32),
  10.     `transaction_service_group` VARCHAR(32),
  11.     `transaction_name`          VARCHAR(128),
  12.     `timeout`                   INT,
  13.     `begin_time`                BIGINT,
  14.     `application_data`          VARCHAR(2000),
  15.     `gmt_create`                DATETIME,
  16.     `gmt_modified`              DATETIME,
  17.     PRIMARY KEY (`xid`),
  18.     KEY `idx_status_gmt_modified` (`status` , `gmt_modified`),
  19.     KEY `idx_transaction_id` (`transaction_id`)
  20. ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COMMENT = '全局事务表';
  21. -- the table to store BranchSession data
  22. CREATE TABLE IF NOT EXISTS `branch_table`
  23. (
  24.     `branch_id`         BIGINT       NOT NULL,
  25.     `xid`               VARCHAR(128) NOT NULL,
  26.     `transaction_id`    BIGINT,
  27.     `resource_group_id` VARCHAR(32),
  28.     `resource_id`       VARCHAR(256),
  29.     `branch_type`       VARCHAR(8),
  30.     `status`            TINYINT,
  31.     `client_id`         VARCHAR(64),
  32.     `application_data`  VARCHAR(2000),
  33.     `gmt_create`        DATETIME(6),
  34.     `gmt_modified`      DATETIME(6),
  35.     PRIMARY KEY (`branch_id`),
  36.     KEY `idx_xid` (`xid`)
  37. ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COMMENT = '分支事务表';
  38. -- the table to store lock data
  39. CREATE TABLE IF NOT EXISTS `lock_table`
  40. (
  41.     `row_key`        VARCHAR(128) NOT NULL,
  42.     `xid`            VARCHAR(128),
  43.     `transaction_id` BIGINT,
  44.     `branch_id`      BIGINT       NOT NULL,
  45.     `resource_id`    VARCHAR(256),
  46.     `table_name`     VARCHAR(32),
  47.     `pk`             VARCHAR(36),
  48.     `status`         TINYINT      NOT NULL DEFAULT '0' COMMENT '0:locked ,1:rollbacking',
  49.     `gmt_create`     DATETIME,
  50.     `gmt_modified`   DATETIME,
  51.     PRIMARY KEY (`row_key`),
  52.     KEY `idx_status` (`status`),
  53.     KEY `idx_branch_id` (`branch_id`),
  54.     KEY `idx_xid_and_branch_id` (`xid` , `branch_id`)
  55. ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COMMENT = '全局锁表';
  56. CREATE TABLE IF NOT EXISTS `distributed_lock`
  57. (
  58.     `lock_key`       CHAR(20) NOT NULL,
  59.     `lock_value`     VARCHAR(20) NOT NULL,
  60.     `expire`         BIGINT,
  61.     primary key (`lock_key`)
  62. ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4;
  63. INSERT INTO `distributed_lock` (lock_key, lock_value, expire) VALUES ('AsyncCommitting', ' ', 0);
  64. INSERT INTO `distributed_lock` (lock_key, lock_value, expire) VALUES ('RetryCommitting', ' ', 0);
  65. INSERT INTO `distributed_lock` (lock_key, lock_value, expire) VALUES ('RetryRollbacking', ' ', 0);
  66. INSERT INTO `distributed_lock` (lock_key, lock_value, expire) VALUES ('TxTimeoutCheck', ' ', 0);
复制代码
如果采用AT模式,那么每个业务数据库还需建一个undo_log表
  1. -- for AT mode you must to init this sql for you business database. the seata server not need it.
  2. CREATE TABLE IF NOT EXISTS `undo_log`
  3. (
  4.     `branch_id`     BIGINT       NOT NULL COMMENT 'branch transaction id',
  5.     `xid`           VARCHAR(128) NOT NULL COMMENT 'global transaction id',
  6.     `context`       VARCHAR(128) NOT NULL COMMENT 'undo_log context,such as serialization',
  7.     `rollback_info` LONGBLOB     NOT NULL COMMENT 'rollback info',
  8.     `log_status`    INT(11)      NOT NULL COMMENT '0:normal status,1:defense status',
  9.     `log_created`   DATETIME(6)  NOT NULL COMMENT 'create datetime',
  10.     `log_modified`  DATETIME(6)  NOT NULL COMMENT 'modify datetime',
  11.     UNIQUE KEY `ux_undo_log` (`xid`, `branch_id`)
  12. ) ENGINE = InnoDB AUTO_INCREMENT = 1 DEFAULT CHARSET = utf8mb4 COMMENT ='AT transaction mode undo table';
复制代码

启动

  • 源码启动: 执行ServerApplication.java的main方法
  • 命令启动: seata-server.sh -h 127.0.0.1 -p 8091 -m db

    • -h: 注册到注册中心的ip
    • -p: Server rpc 监听端口
    • -m: 全局事务会话信息存储模式,file、db、redis,优先读取启动参数
    • -n: Server node,多个Server时,需区分各自节点,用于生成不同区间的transactionId,以免冲突
    • -e: 多环境配置参考 http://seata.io/en-us/docs/ops/multi-configuration-isolation.html 

2.  业务系统集成 Seata Client
步骤一:添加seata依赖(建议单选)

  • 依赖seata-all
  • 依赖seata-spring-boot-starter,支持yml、properties配置(.conf可删除),内部已依赖seata-all
  • 依赖spring-cloud-alibaba-seata,内部集成了seata,并实现了xid传递
步骤二:undo_log建表、配置参数(仅AT模式)
https://seata.io/zh-cn/docs/user/configurations.html
步骤三:数据源代理(不支持自动和手动配置并存)
1、如果使用seata-all
自动配置由注解@EnableAutoDataSourceProxy开启,并可选择jdk proxy或者cglib proxy。
如果采用XA模式,@EnableAutoDataSourceProxy(dataSourceProxyMode = "XA")
手动配置参考如下:
  1. @Primary
  2. @Bean("dataSource")
  3. public DataSource dataSource(DataSource druidDataSource) {
  4.     //AT 代理 二选一
  5.     return new DataSourceProxy(druidDataSource);
  6.     //XA 代理
  7.     return new DataSourceProxyXA(druidDataSource)
  8. }
复制代码
2、如果使用seata-starter
默认就开启了自动代理数据源,无需额外配置
如果使用自动代理数据源时,如果使用XA模式还需要调整配置文件application.yml
  1. seata:
  2.   data-source-proxy-mode: XA
复制代码
如果想要关闭seata-spring-boot-starter的数据源自动代理,可调整配置文件application.yml
  1. seata:
  2.   enable-auto-data-source-proxy: false
复制代码
步骤四:初始化GlobalTransactionScanner
自动,引入seata-spring-boot-starter、spring-cloud-starter-alibaba-seata等jar即可
手动
  1. @Bean
  2. public GlobalTransactionScanner globalTransactionScanner() {
  3.    String applicationName = this.applicationContext.getEnvironment().getProperty("spring.application.name");
  4.    String txServiceGroup = this.seataProperties.getTxServiceGroup();
  5.    if (StringUtils.isEmpty(txServiceGroup)) {
  6.        txServiceGroup = applicationName + "-fescar-service-group";
  7.        this.seataProperties.setTxServiceGroup(txServiceGroup);
  8.    }
  9.    return new GlobalTransactionScanner(applicationName, txServiceGroup);
  10. }
复制代码
步骤五:业务使用
只需在业务方法上加上@GlobalTransactional 注解即可
3.  示例代码
此处用官网的那个案例,调用关系如图:

首先,建库建表,脚本如下:
SQL脚本
  1. CREATE DATABASE `account`;
  2. USE `account`;
  3. DROP TABLE IF EXISTS `t_account`;
  4. CREATE TABLE `t_account` (
  5.   `id` int NOT NULL AUTO_INCREMENT,
  6.   `user_id` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  7.   `amount` double(14,2) DEFAULT '0.00',
  8.   PRIMARY KEY (`id`)
  9. ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
  10. INSERT INTO `t_account` VALUES (1,'1',79.90);
  11. DROP TABLE IF EXISTS `undo_log`;
  12. CREATE TABLE `undo_log` (
  13.   `branch_id` bigint NOT NULL COMMENT 'branch transaction id',
  14.   `xid` varchar(128) NOT NULL COMMENT 'global transaction id',
  15.   `context` varchar(128) NOT NULL COMMENT 'undo_log context,such as serialization',
  16.   `rollback_info` longblob NOT NULL COMMENT 'rollback info',
  17.   `log_status` int NOT NULL COMMENT '0:normal status,1:defense status',
  18.   `log_created` datetime(6) NOT NULL COMMENT 'create datetime',
  19.   `log_modified` datetime(6) NOT NULL COMMENT 'modify datetime',
  20.   UNIQUE KEY `ux_undo_log` (`xid`,`branch_id`)
  21. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='AT transaction mode undo table';
  22. CREATE DATABASE `order`;
  23. USE `order`;
  24. DROP TABLE IF EXISTS `t_order`;
  25. CREATE TABLE `t_order` (
  26.   `id` int NOT NULL AUTO_INCREMENT,
  27.   `order_no` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  28.   `user_id` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  29.   `commodity_code` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  30.   `count` int DEFAULT '0',
  31.   `amount` double(14,2) DEFAULT '0.00',
  32.   PRIMARY KEY (`id`)
  33. ) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
  34. DROP TABLE IF EXISTS `undo_log`;
  35. CREATE TABLE `undo_log` (
  36.   `branch_id` bigint NOT NULL COMMENT 'branch transaction id',
  37.   `xid` varchar(128) NOT NULL COMMENT 'global transaction id',
  38.   `context` varchar(128) NOT NULL COMMENT 'undo_log context,such as serialization',
  39.   `rollback_info` longblob NOT NULL COMMENT 'rollback info',
  40.   `log_status` int NOT NULL COMMENT '0:normal status,1:defense status',
  41.   `log_created` datetime(6) NOT NULL COMMENT 'create datetime',
  42.   `log_modified` datetime(6) NOT NULL COMMENT 'modify datetime',
  43.   UNIQUE KEY `ux_undo_log` (`xid`,`branch_id`)
  44. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='AT transaction mode undo table';
  45. CREATE DATABASE `stock`;
  46. USE `stock`;
  47. DROP TABLE IF EXISTS `t_stock`;
  48. CREATE TABLE `t_stock` (
  49.   `id` int NOT NULL AUTO_INCREMENT,
  50.   `commodity_code` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  51.   `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  52.   `count` int DEFAULT '0',
  53.   PRIMARY KEY (`id`),
  54.   UNIQUE KEY `commodity_code` (`commodity_code`)
  55. ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
  56. INSERT INTO `t_stock` VALUES (1,'A001','立白洗洁精',7);
  57. DROP TABLE IF EXISTS `undo_log`;
  58. CREATE TABLE `undo_log` (
  59.   `branch_id` bigint NOT NULL COMMENT 'branch transaction id',
  60.   `xid` varchar(128) NOT NULL COMMENT 'global transaction id',
  61.   `context` varchar(128) NOT NULL COMMENT 'undo_log context,such as serialization',
  62.   `rollback_info` longblob NOT NULL COMMENT 'rollback info',
  63.   `log_status` int NOT NULL COMMENT '0:normal status,1:defense status',
  64.   `log_created` datetime(6) NOT NULL COMMENT 'create datetime',
  65.   `log_modified` datetime(6) NOT NULL COMMENT 'modify datetime',
  66.   UNIQUE KEY `ux_undo_log` (`xid`,`branch_id`)
  67. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='AT transaction mode undo table';
复制代码
注意版本:示例中使用的框架为 Spring Boot + Mybatis-Plus + Dubbo + Seata
虽然Seata最新版本是1.5.2,Dubbo最新版本为3.1.1,但这这两个版本中二者不兼容,可以降低其中一个的版本,比如
Seata 1.4.2 + Dubbo 3.1.1  或者  Seata 1.5.2 + Dubbo 2.7.18
本示例中采用的是 seata-spring-boot-starter 1.5.2 + dubbo 2.7.18
工程结构如图

父pom.xml如下
  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2.          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  3.     <modelVersion>4.0.0</modelVersion>
  4.     <groupId>com.cjs.example</groupId>
  5.     <artifactId>seata-spring-boot-starter-samples</artifactId>
  6.     <version>1.0-SNAPSHOT</version>
  7.     <packaging>pom</packaging>
  8.     <name>seata-spring-boot-starter-samples</name>
  9.     <modules>
  10.         <module>samples-common-service</module>
  11.         <module>samples-stock-service</module>
  12.         <module>samples-order-service</module>
  13.         <module>samples-account-service</module>
  14.         <module>samples-business-service</module>
  15.     </modules>
  16.     <properties>
  17.         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  18.         <spring-boot.version>2.7.5</spring-boot.version>
  19.         <dubbo.version>2.7.18</dubbo.version>
  20.         <seata.version>1.5.2</seata.version>
  21.         <mybatis-plus.version>3.5.2</mybatis-plus.version>
  22.     </properties>
  23.     <dependencies>
  24.         <dependency>
  25.             <groupId>org.springframework.boot</groupId>
  26.             <artifactId>spring-boot-starter-web</artifactId>
  27.         </dependency>
  28.         <dependency>
  29.             <groupId>org.projectlombok</groupId>
  30.             <artifactId>lombok</artifactId>
  31.             <optional>true</optional>
  32.         </dependency>
  33.     </dependencies>
  34.     <dependencyManagement>
  35.         <dependencies>
  36.             <dependency>
  37.                 <groupId>org.springframework.boot</groupId>
  38.                 <artifactId>spring-boot-dependencies</artifactId>
  39.                 <version>${spring-boot.version}</version>
  40.                 <type>pom</type>
  41.                 <scope>import</scope>
  42.             </dependency>
  43.             
  44.             <dependency>
  45.                 <groupId>org.apache.dubbo</groupId>
  46.                 <artifactId>dubbo</artifactId>
  47.                 <version>${dubbo.version}</version>
  48.             </dependency>
  49.             <dependency>
  50.                 <groupId>org.apache.dubbo</groupId>
  51.                 <artifactId>dubbo-spring-boot-starter</artifactId>
  52.                 <version>${dubbo.version}</version>
  53.             </dependency>
  54.             <dependency>
  55.                 <groupId>org.apache.dubbo</groupId>
  56.                 <artifactId>dubbo-registry-nacos</artifactId>
  57.                 <version>${dubbo.version}</version>
  58.             </dependency>
  59.             <dependency>
  60.                 <groupId>io.seata</groupId>
  61.                 <artifactId>seata-spring-boot-starter</artifactId>
  62.                 <version>${seata.version}</version>
  63.             </dependency>
  64.             <dependency>
  65.                 <groupId>com.baomidou</groupId>
  66.                 <artifactId>mybatis-plus-boot-starter</artifactId>
  67.                 <version>${mybatis-plus.version}</version>
  68.             </dependency>
  69.         </dependencies>
  70.     </dependencyManagement>
  71. </project>
复制代码
子pom.xml如下,其它几个类似不再重复:
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project
  3.     xmlns="http://maven.apache.org/POM/4.0.0"
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5.         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  6.     <modelVersion>4.0.0</modelVersion>
  7.     <parent>
  8.         <groupId>com.cjs.example</groupId>
  9.         <artifactId>seata-spring-boot-starter-samples</artifactId>
  10.         <version>1.0-SNAPSHOT</version>
  11.     </parent>
  12.     <groupId>com.cjs.example</groupId>
  13.     <artifactId>samples-order-service</artifactId>
  14.     <version>${parent.version}</version>
  15.     <name>samples-order-service</name>
  16.     <properties>
  17.         <java.version>1.8</java.version>
  18.     </properties>
  19.     <dependencies>
  20.         <dependency>
  21.             <groupId>com.cjs.example</groupId>
  22.             <artifactId>samples-common-service</artifactId>
  23.             <version>${parent.version}</version>
  24.         </dependency>
  25.         <dependency>
  26.             <groupId>org.apache.dubbo</groupId>
  27.             <artifactId>dubbo</artifactId>
  28.         </dependency>
  29.         <dependency>
  30.             <groupId>org.apache.dubbo</groupId>
  31.             <artifactId>dubbo-spring-boot-starter</artifactId>
  32.         </dependency>
  33.         <dependency>
  34.             <groupId>org.apache.dubbo</groupId>
  35.             <artifactId>dubbo-registry-nacos</artifactId>
  36.         </dependency>
  37.         <dependency>
  38.             <groupId>io.seata</groupId>
  39.             <artifactId>seata-spring-boot-starter</artifactId>
  40.         </dependency>
  41.         <dependency>
  42.             <groupId>com.baomidou</groupId>
  43.             <artifactId>mybatis-plus-boot-starter</artifactId>
  44.         </dependency>
  45.         <dependency>
  46.             <groupId>mysql</groupId>
  47.             <artifactId>mysql-connector-java</artifactId>
  48.             <scope>runtime</scope>
  49.         </dependency>
  50.         <dependency>
  51.             <groupId>org.springframework.boot</groupId>
  52.             <artifactId>spring-boot-starter-test</artifactId>
  53.             <scope>test</scope>
  54.         </dependency>
  55.     </dependencies>
  56.     <build>
  57.         <plugins>
  58.             <plugin>
  59.                 <groupId>org.springframework.boot</groupId>
  60.                 <artifactId>spring-boot-maven-plugin</artifactId>
  61.             </plugin>
  62.         </plugins>
  63.     </build>
  64. </project>
复制代码
application.yml
  1. server:
  2.   port: 8083
  3.   servlet:
  4.     context-path: /order
  5. spring:
  6.   application:
  7.     name: samples-order-service
  8.   datasource:
  9.     driver-class-name: com.mysql.cj.jdbc.Driver
  10.     url: jdbc:mysql://127.0.0.1:3306/order?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
  11.     username: root
  12.     password: 123456
  13. dubbo:
  14.   protocol:
  15.     name: dubbo
  16.     port: 20883
  17.   registry:
  18.     address: nacos://127.0.0.1:8848
  19.   config-center:
  20.     address: nacos://127.0.0.1:8848
  21.   metadata-report:
  22.     address: nacos://127.0.0.1:8848
  23. seata:
  24.   enabled: true
  25.   tx-service-group: my_test_tx_group
  26.   service:
  27.     vgroup-mapping:
  28.       my_test_tx_group: default
  29.   registry:
  30.     type: nacos
  31.     nacos:
  32.       server-addr: 127.0.0.1:8848
  33.       cluster: default
  34.       group: SEATA_GROUP
复制代码
核心代码如下

依次启动这四个项目,Postman访问一下

通过断点,观察 global_table、lock_table、branch_table 等表数据的变化
刚开始,所有表中数据都是空的
执行到事务方法之后,global_table表中有了一条数据

当调用第一个远程接口扣减库存后,lock_table和branch_table表中都有了一条数据


同时,stock库中undo_log表中也新增了一条数据


继续往下执行,当调用第二个远程接口创建订单后,branch_table和lock_table中都新增了2条数据


account库和order库中的undo_log也有了数据

当事务方法执行完后,事务提交,上述表中此次事务相关数据清空
我们通过Seata Server的日志可以更清晰的看到事务从创建到提交的整个过程

正式正常事务成功的情况,有时候由于业务报错了,或者事务超时了,或者其它的情况,事务会回滚

4.  配置中心



在此之前,示例中没有使用配置中心,而是采用本地配置文件的方式。但实际开发过程中,建议还是采用配置中心,下面以nacos作为配置中心演示。
细心的同学会发现,微服务架构中有配置中心和注册中心,Dubbo中也有配置中心和注册中心,而本文讲的Seata也有配置中心和注册中心。那么它们有什么区别吗?其实,并没有区别,各是各的。微服务的配置中心和注册中心你要配置,Dubbo的你也要配置,Seata的配置中心和注册中心你还要配置,尽管它们可能是同一个实例,但那也得各配各的。
  1. <dependency>
  2.     <groupId>com.alibaba.nacos</groupId>
  3.     <artifactId>nacos-client</artifactId>
  4.     <version>2.1.1</version>
  5. </dependency>
复制代码
有两种配置方式
方式一:放在某个命名空间下,每一个配置项作为一行,即每一行一个DataId
https://github.com/seata/seata/tree/master/script/config-center

在scripts/config-center目录下有个config.txt,这个config.txt文件中为我们准备好了各种配置项,我们按需修改里面的内容即可,然后可以通过脚本将config.txt中的内容导入nacos,当然也可以一条一条手动在nacos中创建
例如:
  1. sh ${SEATAPATH}/script/config-center/nacos/nacos-config.sh -h localhost -p 8848 -g SEATA_GROUP -t 5a3c7d6c-f497-4d68-a71a-2e5e3340b3ca -u username -w password
复制代码
注意:-g 指定Group  -t 指定命名空间
示例中上传到默认命名空间下了


注意,config.txt中包含了Server端和Client端的配置,里面注释写的也比较清楚哪些是Server端需要的配置,哪些是Client端的配置
导入配置以后,现在修改Server端的配置,seata-->conf-->application.yml中seata.config部分
  1. seata:
  2.   config:
  3.     type: nacos
  4.     nacos:
  5.       server-addr: 127.0.0.1:8848
  6.       group : "SEATA_GROUP"
  7.       namespace:
  8.       username:
  9.       password:
复制代码
同时,每个业务系统里面的配置也要修改一下
  1. seata:
  2.   config:
  3.     type: nacos
  4.     nacos:
  5.       server-addr: 127.0.0.1:8848
  6.       group : "SEATA_GROUP"
  7.       namespace:
  8.       username:
  9.       password:
复制代码
由于这里导入配置的时候没有-t指定命名空间,即导入到默认命名空间,所以配置里面namespace为空,如果-t指定了特定的命名空间,则server和client端的namespace也要与之对应
方式二:通过dataId配置
首先,需要在nacos新建配置,此处dataId为seataServer.properties
然后,将修改后的config.txt内容粘贴进去,保存修改并发布即可


修改Server和Client端seata.config配置
  1. seata:
  2.   config:
  3.     type: nacos
  4.     nacos:
  5.       server-addr: 127.0.0.1:8848
  6.       group: "SEATA_GROUP"
  7.       namespace:
  8.       dataId: "seataServer.properties"
  9.       username:
  10.       password:
复制代码
重启Server和Client即可
 

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

九天猎人

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表