在 spring boot 项目中配置多个数据源的情形在开发中经常会遇见,本文以 Spring Boot + MyBatis 的方式实现 mysql + Postgresql 双数据源项目搭建,具体详细代码请参考:

https://gitee.com/senn-wen/my...

一、依赖配置

pom.xml 文件中引入 postgresql mysql 的驱动文件。

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

<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <scope>runtime</scope>
</dependency>

二、Spring boot 配置

2.1 application.yml 配置

配置需要连接的数据库连接参数,下面的样例配置了 postgresql 和 mysql ,因为我选择了hikariCP 作为连接池,因此在下面配置了下 hikari,如果是线上的服务建议根据实际的服务器性能大小设置好该参数。记住你连接参数的配置路径,后续要使用到。

spring:
  datasource:

    postgresql:
      driver-class-name: org.postgresql.Driver
      url: jdbc:postgresql://url:port/database
      username: postGIS
      password: postGIS

    mysql:
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://url:port/database
      username: root
      password: root
      
    hikari:
      maximum-pool-size: 3
      connection-timeout: 500

2.2 排除Spring datasource 自动化配置依赖

因为 Spring Boot 会进行自动装配你的配置,为了使你自定义配置生效,需求在@SpringBootApplication 中排除掉和 datasoure 相关的配置。主要有三个:

  • 数据源:DataSourceAutoConfiguration.class
  • 事务:DataSourceTransactionManagerAutoConfiguration.class
  • Jdbc模板:JdbcTemplateAutoConfiguration.class
@SpringBootApplication(exclude = {
        DataSourceAutoConfiguration.class,
        DataSourceTransactionManagerAutoConfiguration.class,
        JdbcTemplateAutoConfiguration.class
})
public class PostgresqlApplication {

    public static void main(String[] args) {
        SpringApplication.run(PostgresqlApplication.class, args);
    }

}

三、数据源配置

做完以上基础配置后,就需要配置具体的Bean了,每个数据源的建议独立配置便于后期维护。数据源配置要经历两个主要的步骤:

  • 源数据的配置(读取配置文件、生成新的DataSource)
  • 指定ORM 框架在什么地方使用该数据源

这两个是框架无法赋予你的,只能手动配置。

3.1 MySQL 数据源配置

package com.senn.postgresql.config;

import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @author senn
 * @version 1.0.0
 * @ClassName MsqlDataSourceConfig.java
 * @Description mysql 数据库配置
 * @createTime 2021年01月15日 09:02:00
 */
@Configuration
@Slf4j
@MapperScan(basePackages = "com.senn.postgresql.common.mapper.mysql",
        sqlSessionFactoryRef = "mysqlDataSourceFactory")
public class MsqlDataSourceConfig {


    /**
     * @description mysql DataSource Properties 配置
     * @updateTime  2021/1/15 9:04
     */

    @Bean(name = "mysqlDataSourceProperties")
    @ConfigurationProperties("spring.datasource.mysql")
    public DataSourceProperties mysqlDataSourceProperties() {
        return new DataSourceProperties();
    }

    /**
     * @description   mysql DataSource 源配置
     * @updateTime  2021/1/15 9:11
     */
    @Bean(name = "mysqlDataSource")
    @ConfigurationProperties("spring.datasource.mysql.configuration")
    public javax.sql.DataSource mysqlDataSource() {
        DataSourceProperties dataSourceProperties = mysqlDataSourceProperties();
        log.info(dataSourceProperties.getUrl());
        // 数据库连接池设置为 Hikari
        return mysqlDataSourceProperties().initializeDataSourceBuilder().type(HikariDataSource.class).build();
    }


    // 以下内容和 mybatis 相关
    /**
     * @description mysql 工厂配置
     * @updateTime  2021/1/15 9:18
     */
    @Bean("mysqlDataSourceFactory")
    @DependsOn("mysqlDataSource")
    public SqlSessionFactory dataSourceFactory() throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(mysqlDataSource());
        return factoryBean.getObject();
    }

    /**
     * @description mysql session 模板配置
     * @updateTime  2021/1/15 9:22
     */

    @Bean("mysqlSqlSessionTemplate")
    @DependsOn("mysqlDataSourceFactory")
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("mysqlDataSourceFactory") SqlSessionFactory sessionFactory) {
        return new SqlSessionTemplate(sessionFactory);
    }

    /**
     * @description mysql  事务配置
     * @updateTime  2021/1/15 9:22
     */
    @Bean(name = "mysqlTransactionManager")
    @DependsOn("mysqlDataSource")
    public DataSourceTransactionManager mysqlTransactionManager(@Qualifier("mysqlDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

}

Postgresql 数据源配置

package com.senn.postgresql.config;

import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @author senn
 * @version 1.0.0
 * @ClassName DataSourceConfig.java
 * @Description psotgresql 数据库配置
 * @createTime 2021年01月14日 15:56:00
 */
@Configuration
@Slf4j
@MapperScan(basePackages = "com.senn.postgresql.common.mapper.postgresql",
        sqlSessionFactoryRef = "postgresqlDataSourceFactory")
public class PostgresqlDataSourceConfig {


    /**
     * @description postgresql DataSource Properties 配置
     * @updateTime  2021/1/15 9:04
    */

    @Bean(name = "postgresqlDataSourceProperties")
    @ConfigurationProperties("spring.datasource.postgresql")
    public DataSourceProperties postgresqlDataSourceProperties() {
        return new DataSourceProperties();
    }

    /**
     * @description   postgresql DataSource 源配置
     * @param
     * @updateTime  2021/1/15 9:11
     * @throws
    */
    @Bean(name = "postgresqlDataSource")
    @ConfigurationProperties("spring.datasource.postgresql.configuration")
    public DataSource postgresqlDataSource() {
        DataSourceProperties dataSourceProperties = postgresqlDataSourceProperties();
        log.info(dataSourceProperties.getUrl());
        // 数据库连接池设置为 Hikari
        return postgresqlDataSourceProperties().initializeDataSourceBuilder().type(HikariDataSource.class).build();
    }

    // 以下内容和 mybatis 相关

    /**
     * @description postgresql 工程配置
     * @updateTime  2021/1/15 9:18
    */
    @Bean("postgresqlDataSourceFactory")
    @DependsOn("postgresqlDataSource")
    public SqlSessionFactory dataSourceFactory() throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(postgresqlDataSource());
        return factoryBean.getObject();
    }

    /**
     * @description postgresql session 模板配置
     * @updateTime  2021/1/15 9:22
    */

    @Bean("postgresqlSqlSessionTemplate")
    @Primary
    @DependsOn("postgresqlDataSourceFactory")
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("postgresqlDataSourceFactory") SqlSessionFactory sessionFactory) {
        return new SqlSessionTemplate(sessionFactory);
    }

    /**
     * @description postgresql  事务配置
     * @updateTime  2021/1/15 9:22
     */
    @Bean(name = "postgresqlTransactionManager")
    @DependsOn("postgresqlDataSource")
    public DataSourceTransactionManager fawkesTransactionManager(@Qualifier("postgresqlDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

}

@Senn · 森


Senn·森
1 声望0 粉丝