一、背景

在这篇文章中,咱们应用Seata整合一下多数据源的场景。多数据源切换的性能咱们应用dynamic-datasource-spring-boot-starter来实现,并且这个组件还能够和Seata进行整合,实现数据源的代理。

此篇文章 依赖之前的 seata整合nacos实现分布式的部署

二、整合步骤

1、seata server的搭建

seata整合nacos实现分布式的部署

2、引入数据源切换组件

<dependency>    <groupId>com.baomidou</groupId>    <artifactId>dynamic-datasource-spring-boot-starter</artifactId>    <version>3.4.1</version></dependency>

3、引入seata组件

<dependency>   <groupId>io.seata</groupId>    <artifactId>seata-spring-boot-starter</artifactId>    <version>1.4.2</version></dependency><!-- 此处seata的注册核心和配置核心应用的都是nacos,索引须要引入这个 --><dependency>    <groupId>com.alibaba.nacos</groupId>    <artifactId>nacos-client</artifactId>    <version>1.3.2</version></dependency>

4、配置多数据源

  1. 此处配置2个数据源,account和order并且设置和 seata进行整合
  2. 须要注册此切面的地位
  3. 设置默认的数据源
spring:  datasource:    dynamic:      # 启用 seata      seata: true      # 模式是 at 模式      seata-mode: at      # 主数据源是 account 数据源      primary: account      # 不启用严格模式      strict: false      # 配置数据源切面的地位      order: "-2147483648"      # 每一个数据源      datasource:        # account 库的数据源        account:          url: jdbc:mysql://127.0.0.1:3306/seata_account?useUnicode=true&characterEncoding=utf8&autoReconnectForPools=true&useSSL=false          username: root          password: root          driver-class-name: com.mysql.cj.jdbc.Driver        # 订单库的数据源        order:          url: jdbc:mysql://127.0.0.1:3306/seata_order?useUnicode=true&characterEncoding=utf8&autoReconnectForPools=true&useSSL=false          username: root          password: root          driver-class-name: com.mysql.cj.jdbc.Driver

5、敞开seata本人默认的数据源代理

seata:  # 是否主动开启数据源代理  enable-auto-data-source-proxy: false

6、配置seata事物分组

seata:  enabled: true  tx-service-group: tx_multiple_datasource_group   # 该分组须要在seata server的配置核心中存在,即在 seata server 的配置核心中须要存在service.vgroupMapping.tx_multiple_datasource_group 配置项

7、业务库创立undo_log表

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

8、xid的传递

9、代码中应用数据源切换

10、业务办法开启分布式事物


到此就整合完了。

三、注意事项

1、开启事物,是须要获取一个数据库连贯的,那么咱们的 @DS 注解切换数据源必须要在 @Transaction 之前执行。

四、残缺代码

https://gitee.com/huan1993/spring-cloud-parent/tree/master/seata/seata-multiple-datasource