Spring Boot 多数据源配置(mysql和sqlServer)

1. pom添加依赖
<!-- mysql -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>
<!-- druid -->
<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>druid-spring-boot-starter</artifactId>
	<version>1.1.9</version>
</dependency>
<!-- sqlServer -->
<dependency>
	<groupId>com.microsoft.sqlserver</groupId>
	<artifactId>mssql-jdbc</artifactId>
	<scope>runtime</scope>
</dependency>
2. application.properties配置
#主数据源(Mysql)
spring.datasource.master.name=master
spring.datasource.master.jdbc-url=jdbc:mysql://192.168.0.1:3306/master?useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.master.username=root
spring.datasource.master.password=root
#使用druid数据源
spring.datasource.master.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.master.driver-class-name=com.mysql.jdbc.Driver
#监控统计
spring.datasource.master.filters=stat
#最大连接池数量
spring.datasource.master.maxActive=20
#初始化时建立物理连接的个数
spring.datasource.master.initialSize=1
#获取连接时最大等待时间
spring.datasource.master.maxWait=60000
#最小连接池数量
spring.datasource.master.minIdle=1
#Destroy线程会检测连接的间隔时间,testWhileIdle的判断依据
spring.datasource.master.timeBetweenEvictionRunsMillis=60000
spring.datasource.master.minEvictableIdleTimeMillis=300000
#用来检测连接是否有效的sql
spring.datasource.master.validationQuery=select 'x'
#配置为true,即申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。
spring.datasource.master.testWhileIdle=true
#申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能
spring.datasource.master.testOnBorrow=false
#归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能
spring.datasource.master.testOnReturn=false
#是否缓存preparedStatement,也就是PSCache。PSCache对支持游标的数据库性能提升巨大,比如说oracle。在mysql下建议关闭
spring.datasource.master.poolPreparedStatements=false
#要启用PSCache,必须配置大于0
spring.datasource.master.maxOpenPreparedStatements=-1

#从数据源(SqlServer)
spring.datasource.other.name=other
spring.datasource.other.jdbc-url=jdbc:sqlserver://192.168.0.2:1433;DatabaseName=other
spring.datasource.other.username=sa
spring.datasource.other.password=123456
#使用druid数据源
spring.datasource.other.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.other.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
#监控统计
spring.datasource.other.filters=stat
#最大连接池数量
spring.datasource.other.maxActive=20
#初始化时建立物理连接的个数
spring.datasource.other.initialSize=1
#获取连接时最大等待时间
spring.datasource.other.maxWait=60000
#最小连接池数量
spring.datasource.other.minIdle=1
#Destroy线程会检测连接的间隔时间,testWhileIdle的判断依据
spring.datasource.other.timeBetweenEvictionRunsMillis=60000
spring.datasource.other.minEvictableIdleTimeMillis=300000
#用来检测连接是否有效的sql
spring.datasource.other.validationQuery=select 'x'
#配置为true,即申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。
spring.datasource.other.testWhileIdle=true
#申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能
spring.datasource.other.testOnBorrow=false
#归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能
spring.datasource.other.testOnReturn=false
#是否缓存preparedStatement,也就是PSCache。PSCache对支持游标的数据库性能提升巨大,比如说oracle。在mysql下建议关闭。SqlServer有游标,可开启
spring.datasource.other.poolPreparedStatements=true
#要启用PSCache,必须配置大于0
spring.datasource.other.maxOpenPreparedStatements=20
3. Mysql配置
package com.xpf.dao.conf;

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.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @Title:MasterDBConfig
 * @Package:com.xpf.dao.conf
 * @Author: xiapf
 * @Date:2019/8/30
 * @Descrption: 数据源配置
 */

@Configuration
@MapperScan(basePackages = "com.xpf.dao.master", sqlSessionFactoryRef = "masterSqlSessionFactory")
public class MasterDbConfig {

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

    @Primary
    @Bean(name = "masterSqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("masterDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        factoryBean.setTypeAliasesPackage("com.xpf.bean");
        factoryBean.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/master/*/*.xml"));
        return factoryBean.getObject();
    }

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

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

4. SqlServer配置
package com.xpf.dao.conf;

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.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @Title:OtherDbConfig
 * @Package:com.xpf.dao.conf
 * @Author: xiapf
 * @Date:2019/8/30
 * @Descrption: 数据源配置
 */

@Configuration
@MapperScan(basePackages = "com.xpf.dao.other", sqlSessionFactoryRef = "otherSqlSessionFactory")
public class OtherDbConfig {

    @Bean(name = "otherDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.other")
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "otherTransactionManager")
    public DataSourceTransactionManager transactionManager(@Qualifier("otherDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);

    }

    @Bean(name = "otherSqlSessionFactory")
    public SqlSessionFactory basicSqlSessionFactory(@Qualifier("otherDataSource") DataSource basicDataSource) throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(basicDataSource);
        factoryBean.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/other/*/*.xml"));
        return factoryBean.getObject();
    }

    @Bean(name = "otherSqlSessionTemplate")
    public SqlSessionTemplate testSqlSessionTemplate(
            @Qualifier("otherSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}
  • @ConfigurationProperties(prefix = “spring.datasource.master”):在application.properties中通过前缀为spring.datasource.master 的来设置

  • @Bean:等同于之前在xml里的配置Bean

  • @Qualifier:指定注入的Bean的名称,使用byName方式寻找合格的bean

  • @Primary:用primary注解其中一个bean就要优先于其他的Bean

参考:https://blog.csdn.net/weixin_33897722/article/details/86012469

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐