SpringBoot多数据源yaml配置

1.配置多数据源

  1. pom文件
    1. <dependency>
      <groupId>com.baomidou</groupId>
      <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
      <version>2.5.6</version>
      </dependency>
  2. yaml文件(一定对齐)  
    1. 第一种

       

       

      spring:  
        datasource:
          dynamic:
            primary: db1
            datasource:
              db1:
                username: root
                password: root
                url: jdbc:mysql://127.0.0.1:3306/db1
                driver-class-name: com.mysql.jdbc.Driver
                type: com.alibaba.druid.pool.DruidDataSource
              db2:
                username: root2
                password: root2
                url: jdbc:mysql://127.0.0.1:3306/db2
                driver-class-name: com.mysql.jdbc.Driver
                type: com.alibaba.druid.pool.DruidDataSource
    2. 第二种 
      spring:  
        datasource:
          dynamic:
            datasource:
              master_db1:
                username: root
                password: root
                url: jdbc:mysql://127.0.0.1:3306/db1
                driver-class-name: com.mysql.jdbc.Driver
                type: com.alibaba.druid.pool.DruidDataSource
              db2:
                username: root2
                password: root2
                url: jdbc:mysql://127.0.0.1:3306/db2
                driver-class-name: com.mysql.jdbc.Driver
                type: com.alibaba.druid.pool.DruidDataSource
              druid:
                initial-size: 20
                minIdle: 50  #最小连接池数量
                xxxxxxxxx 

2.设置默认数据源

  配置中的  primary: db1  , 即是指定默认使用的数据库

 spring:
  datasource:
    dynamic:
      primary: db1

3.使用注解切换数据源

  1. 类上
    @DS("db2")
    public class xxx(){}
  2. 方法上
    @DS("db2")
    public void xxx(){}
  3.  mapper方法上
    @Select("SELECT SFZH,USER_NAME,SEX FROM T_USER_INFO WHERE A = #{A}")
    @DS("db2")
    Map<String, Object> queryView(@Param("A") String A);

4.其他配置 , 启动

修改Application注解
@SpringBootApplication(exclude = DruidDataSourceAutoConfigure.class)

 

posted @ 2022-06-21 17:10  反转苹果派  阅读(1806)  评论(0编辑  收藏  举报