SpringCloud整合nacos、seata接入多数据源

1、环境准备
工具版本
windowswin11
idea2023.1.2
JDK1.8
maven3.9.0
SpringBoot2.7.16
SpringCloud2021.0.5
SpringCloudAlibaba2021.0.5.0
2、seata、nacos服务端的下载与启动

nacos(2.2.0)下载链接(注意:客户端nacos版本为2.2.0必须与服务端一致Releases · alibaba/nacos · GitHuban easy-to-use dynamic service discovery, configuration and service management platform for building cloud native applications. - Releases · alibaba/nacosicon-default.png?t=N7T8https://github.com/alibaba/nacos/releases

下载文件解压后进入nacos文件conf目录下运行mysql-schema.sql脚本

运行完成后如图所示

上述操作完成后在当前目录下打开application.properties文件,将红框中内容该为自己的库&账户信息

从当前文件目录返回上一级目录进入bin目录找到startup.cmd脚本,将脚本中26行改为standalone,默认值为cluster

更改完成后双击startup.cmd成功启动后如图

浏览器输入http://localhost:8848/nacos/index.html进入控制台(nacso默认账户密码都为nacos

seata(1.6.1)下载链接下载中心本文将向你介绍如何点击了解各版本详情和升级注意事项。icon-default.png?t=N7T8https://seata.io/zh-cn/blog/download.html

下载文件解压后进入seata\script\server\db目录当中找到mysql.sql脚本运行

注意:SEATA AT 模式需要 UNDO_LOG 表

-- 注意此处0.3.0+ 增加唯一索引 ux_undo_log
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;

运行完后如图

返回到conf目录找到application.yml文件更改为使用nacos作为注册

seata使用nacos作为注册当中的命名空间及分组需与当前启动的nacos保持一致

使用db作为存储将url、username、password中的数据改为自己的库&账户信息

seata:
  config:
    # support: nacos, consul, apollo, zk, etcd3
    type: nacos
    nacos:
      server-addr: 127.0.0.1:8848
      namespace: stage # 不写则默认为public名称空间
      group: DEFAULT_GROUP
      username: nacos # nacos的账号密码
      password: nacos
      # if use MSE Nacos with auth, mutex with username/password attribute
      #access-key: ""
      #secret-key: ""
      #data-id:
  registry:
    # support: nacos, eureka, redis, zk, consul, etcd3, sofa
    type: nacos
    nacos:
      application: seata-server  # 指定注册至nacos注册中心的服务名,需要和${spring.application.name} 保持一致
      server-addr: 127.0.0.1:8848
      group: DEFAULT_GROUP
      namespace: stage
      cluster: default # 指定seata注册值nacos的集群名为default
      username: nacos
      password: nacos
      ##if use MSE Nacos with auth, mutex with username/password attribute
      #access-key: ""
      #secret-key: ""
  store:
    # support: file 、 db 、 redis
    mode: db
    db:
      datasource: druid
      db-type: mysql
      driver-class-name: com.mysql.jdbc.Driver
      url: jdbc:mysql://127.0.0.1:3306/nacos_seata?rewriteBatchedStatements=true&useUnicode=true
      user: root
      password: 123456
      min-conn: 5
      max-conn: 100
      global-table: global_table
      branch-table: branch_table
      lock-table: lock_table
      distributed-lock-table: distributed_lock
      query-limit: 100
      max-wait: 5000

完成上述操作后返回bin目录双击seata-server.bat脚本(注意:启动seata之前必须先启动nacos

浏览器输入http://localhost:7091/#/TransactionInfo进入控制台(seata默认账户密码都为seata)

3、构建项目工程

使用IDEA创建Spring项目工程

项目目录:

pom.xml文件

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.seata</groupId>
    <artifactId>nacos-seata</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>nacos-seata</name>
    <description>nacos-seata</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-bootstrap</artifactId>
            <version>3.1.4</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</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>
            <version>2.3.1</version>
        </dependency>

        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
        </dependency>

        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </dependency>

        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
            <version>2021.0.5.0</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
            <version>2021.0.5.0</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-seata</artifactId>
            <version>2021.0.5.0</version>
            <exclusions>
                <exclusion>
                    <groupId>io.seata</groupId>
                    <artifactId>seata-spring-boot-starter</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>io.seata</groupId>
                    <artifactId>seata-all</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>io.seata</groupId>
            <artifactId>seata-spring-boot-starter</artifactId>
            <version>1.6.1</version>
        </dependency>

        <dependency>
            <groupId>io.seata</groupId>
            <artifactId>seata-all</artifactId>
            <version>1.6.1</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>2021.0.5</version>
                <scope>import</scope>
                <type>pom</type>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>2.7.16</version>
                <scope>import</scope>
                <type>pom</type>
            </dependency>
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>2021.0.5.0</version>
                <scope>import</scope>
                <type>pom</type>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

启动类NacosSeataApplication

nacos中项目配置

nacos-seata.yml(配置文件中的namespace、group也需与当前nacos保持一致)

spring: 
  cloud: 
    alibaba:
      seata:
        tx-service-group: ${seata.tx-service-group}
  datasource:
    master:
      driver-class-name: com.mysql.cj.jdbc.Driver
      jdbc-url: jdbc:mysql://127.0.0.1:3306/myself_dev?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=GMT%2B8
      username: root
      password: 123456
    slave:
      driver-class-name: org.postgresql.Driver
      jdbc-url: jdbc:postgresql://127.0.0.1:5432/postgres?serverTimezone=GMT%2B8&currentSchema=public&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false
      username: postgres
      password: 123456

seata:
  application-id: seata-server
  # 使用的事务组
  tx-service-group: ${spring.application.name}-group
  # 开启自动源数据代理
  enable-auto-data-source-proxy: true
  service:
    # 事务组对应的集群名称
    vgroup-mapping:
      ${seata.tx-service-group}: default
    # 是否禁用全局事务
    disable-global-transaction: false
  registry:
    type: nacos
    nacos:
      application: seata-server
      namespace: stage
      server-addr: 127.0.0.1:8848
      group: DEFAULT_GROUP
      cluster: default
      username: ${spring.cloud.nacos.discovery.username}
      password: ${spring.cloud.nacos.discovery.password}
  config:
    type: nacos
    nacos:
      namespace: stage
      server-addr: 127.0.0.1:8848
      group: DEFAULT_GROUP
      username: ${spring.cloud.nacos.discovery.username}
      password: ${spring.cloud.nacos.discovery.password}
  enabled: true

mybatis:
  configuration:
    map-underscore-to-camel-case: true
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  type-aliases-package: com.seata.seatanacos.domain  

nacos当前命名空间下需增加下面配置

项目bootstrap.yml配置文件

多数据源配置

mysql配置

@Configuration
@MapperScan(basePackages = "com.seata.nacosseata.mapper.master", sqlSessionTemplateRef = "MasterSqlSessionTemplate")
public class MySqlDataSourceConfig {

    @Bean(name = "MasterDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.master")
    @Primary
    public DataSource masterDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "MasterSqlSessionFactory")
    @Primary
    public SqlSessionFactory masterSqlSessionFactory(@Qualifier("MasterDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/master/*.xml"));
        return bean.getObject();
    }

    @Bean(name = "MasterTransactionManager")
    @Primary
    public DataSourceTransactionManager masterTransactionManager(@Qualifier("MasterDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "MasterSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate masterSqlSessionTemplate(@Qualifier("MasterSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}

postgresql配置

@Configuration
@MapperScan(basePackages = "com.seata.nacosseata.mapper.slave", sqlSessionTemplateRef = "SlaveSqlSessionTemplate")
public class PostGreSqlDataSourceConfig {

    @Bean(name = "SlaveDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.slave")
    public DataSource slaveDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "SlaveSqlSessionFactory")
    public SqlSessionFactory slaveSqlSessionFactory(@Qualifier("SlaveDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/slave/*.xml"));
        return bean.getObject();
    }

    @Bean(name = "SlaveTransactionManager")
    public DataSourceTransactionManager slaveTransactionManager(@Qualifier("SlaveDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "SlaveSqlSessionTemplate")
    public SqlSessionTemplate slaveSqlSessionTemplate(@Qualifier("SlaveSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}

项目启动后出现下图即seata注册成功

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值