SpringBoot集成dynamic-datasource实现多数据源自动注入

  • Post author:
  • Post category:其他

springboot在集成dynamic-datasource后配置多数据源其实还是很简单的。

pom依赖

        <!-- dynamic-datasource 依赖-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
            <version>3.1.0</version>
        </dependency>
        <!--druid连接池-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>${druid.version}</version>
        </dependency>

示例使用的是druid连接池。

配置文件

spring:
  datasource:
    dynamic:
      primary: master
      datasource:
        master:
          type: com.alibaba.druid.pool.DruidDataSource
          driver-class-name: com.mysql.jdbc.Driver
          url: jdbc:mysql://127.0.0.1:3306/master_db?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8&useSSL=false
          username: root
          password: 密码
        second:
          type: com.alibaba.druid.pool.DruidDataSource
          driver-class-name: com.mysql.jdbc.Driver
          url: jdbc:mysql://127.0.0.1:3306/second_db?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8&useSSL=false
          username: root
          password: 密码

        需要注意dynamic下的层级结构,还有primary: master指定主驱动的名称

SpringBootApplication启动类

@SpringBootApplication(exclude = DruidDataSourceAutoConfigure.class)
@EnableTransactionManagement
public class MultipleDataSources {
    public static void main(String[] args) {
        SpringApplication.run(MultipleDataSources.class, args);
    }
}

需要排除DruidDataSourceAutoConfigure会按原生spring:datasource 下的结构找数据库链接配置

使用@DS注解

@Mapper
@DS("master")
public interface MasterMapper extends BaseMapper<MasterEntity> {
}
@Mapper
@DS("second")
public interface SecondMapper extends BaseMapper<SecondEntity> {
}

   @DS(“配置的数据源名称”),@DS注解可以加在mapper、service、以及执行数据库操作的方法上


版权声明:本文为love13135816原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。