SpringBoot配置数据库多数据源

框架:SpringBoot

介绍

在实际项目开发中,也许会遇到这样一个需求:目前有两家企业数据共享(这里就用A、B区分这两家公司吧)B公司是做业务代码开发,数据来源部分由A公司提供,还有部分是由B公司自己维护的一些数据。这时,在项目开发时就不得不想办法如何配置多数据源了。

实施

步骤一:首先在pom文件中引入配置多数据源依赖这里介绍使用如下:

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

现在有了上面依赖,配置多数据源则只需要在application.yaml或者是application.properties文件中配置相关数据库连接等信息。

步骤二:在配置文件中新增以下内容(以 application.yaml 文件为例)

spring:
  datasource:
    dynamic:
      primary: [数据库1库名] #设置默认的数据源或者数据源组,默认值即为[数据库1库名]
      strict: false #严格匹配数据源,默认false. true未匹配到指定数据源时抛异常,false使用默认数据源
      datasource:
        [数据库1库名]:
          url: jdbc:postgresql://xxx.xxx.x.xxx:5432/[数据库1库名]?serverTimezone=UTC
          driver-class-name: org.postgresql.Driver
          username: [数据库1用户名]
          password: [数据库1密码]
        [数据库2库名]:
          url: jdbc:mysql://xxx.xxx.x.xxx:3306/[数据库2库名]?serverTimezone=UTC
          username: [数据库2用户名]
          password: [数据库2密码]
          driver-class-name: com.mysql.cj.jdbc.Driver

步骤三:使用==@DS==切换数据源

@DS 可以注解在方法上或类上,同时存在就近原则 方法上注解 优先于 类上注解

注解

结果

没有@DS

使用默认的数据源(primary: [数据库1库名])

@DS(“数据库2库名”)

使用指定的数据源(使用 数据库2)

@DS("数据库1库名")
@Mapper
public interface BasicLivingsMapper extends BaseMapper<BasicLivings> {
    //获取/修改都是数据库1的数据
}
// 当然因为在yaml文件指定了默认使用的数据库,也可以替换成下面这样
@Mapper
public interface BasicLivingsMapper extends BaseMapper<BasicLivings> {
    //获取/修改都是数据库1的数据
}

// 如果使用其他数据库
@DS("数据库2库名")
@Mapper
public interface BasicLivingsMapper extends BaseMapper<BasicLivings> {
    //获取/修改都是数据库1的数据
}

可能会遇到的问题

可能在使用过程中会遇到一些问题

问题1:

***************************
APPLICATION FAILED TO START
***************************

Description:

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.

Reason: Failed to determine a suitable driver class


Action:

Consider the following:
	If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
	If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).

这是由于没有在pom文件中引入配置多数据源依赖导致。

问题2:

RuntimeException: Failed to load driver class com.mysql.cj.jdbc.Driver in either of HikariConfig class loader or Thread context classloader

这是由于pom文件缺少mysql驱动,加上相应驱动依赖即可。