springboot hikari连接池配置多数据源 springboot配置多个连接池_spring boot

1.配置文件

配置文件,红框标注的地方都是需要注意的地方,springboot2.x的数据链接池默认使用hikari,所以只需要配置一下即可,这里使用的properties作为配置文件,yml同理,红框中标注的

spring.datasource.url 数据库的 JDBC URL。

spring.datasource.jdbc-url 用来重写自定义连接池

官方文档的解释是:

因为连接池的实际类型没有被公开,所以在您的自定义数据源的元数据中没有生成密钥,而且在IDE中没有完成(因为DataSource接口没有暴露属性)。另外,如果您碰巧在类路径上有Hikari,那么这个基本设置就不起作用了,因为Hikari没有url属性(但是确实有一个jdbcUrl属性)。在这种情况下,您必须重写您的配置如下:


当遇到 项目启动时 jdbcUrl is required with driverClassName这个错误时,注意看一下上面这部分的配置是否有问题↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑

报错信息为
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Unsatisfied dependency expressed through method 'entityManagerFactory' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactoryBuilder' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Unsatisfied dependency expressed through method 'entityManagerFactoryBuilder' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaVendorAdapter' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.JpaVendorAdapter]: Factory method 'jpaVendorAdapter' threw exception; nested exception is java.lang.IllegalArgumentException: jdbcUrl is required with driverClassName.

2.数据源配置类

package com.***.***.config;

import javax.sql.DataSource;

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.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import com.zaxxer.hikari.HikariDataSource;

@Configuration
//扫描 Mapper 接口并容器管理
@MapperScan(basePackages = "com.***.***.dao.mapper", sqlSessionFactoryRef = "sqlserverSqlSessionFactory")
public class MysqlConfig {
	/**
     * @Bean 注册Bean对象
     * @Primary 表示默认数据源
     * @ConfigurationProperties 读取properties中的配置参数映射成为一个对象
     */
    @Bean(name = "sqlserverDataSource")
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.primary")
    public HikariDataSource getSqlserverDateSource() {
        return new HikariDataSource();
    }

    /**
     * @param datasource 数据源
     * @return SqlSessionFactory
     * @Primary 默认SqlSessionFactory
     */
    @Bean(name = "sqlserverSqlSessionFactory")
    @Primary
    public SqlSessionFactory sqlserverSqlSessionFactory(@Qualifier("sqlserverDataSource") DataSource datasource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(datasource);
        //mybatis扫描xml所在位置
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/*.xml"));
        //分页插件
//        Interceptor interceptor = new PageInterceptor();
//        Properties properties = new Properties();
        //数据库
//        properties.setProperty("helperDialect", "sqlserver");
//        //是否将参数offset作为PageNum使用
//        properties.setProperty("offsetAsPageNum", "true");
//        //是否进行count查询
//        properties.setProperty("rowBoundsWithCount", "true");
        //是否分页合理化
//        properties.setProperty("reasonable", "true");
//        interceptor.setProperties(properties);
//        bean.setPlugins(new Interceptor[] {interceptor});
        return bean.getObject();
    }

    @Bean("sqlserverSessionTemplate")
    @Primary
    public SqlSessionTemplate sqlserverSqlSessionTemplate(@Qualifier("sqlserverSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

第二个数据源配置类

package com.***.***.config;

import java.util.Properties;

import javax.sql.DataSource;

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.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import com.zaxxer.hikari.HikariDataSource;

@Configuration
@MapperScan(basePackages = "com.***.***.dao.zhilianMapper", sqlSessionFactoryRef = "zhilianSessionFactory")
public class MysqlZhilianConfig {

	/**
	 * @Bean 注册Bean对象
	 * @Primary 表示默认数据源
	 * @ConfigurationProperties 读取properties中的配置参数映射成为一个对象
	 */
	@Bean(name = "zhilianyDataSource")
	@ConfigurationProperties(prefix = "spring.datasource.secondary")
	public HikariDataSource getMysqlDateSource() {
		return new HikariDataSource();
	}

	/**
	 * @param datasource 数据源
	 * @return SqlSessionFactory
	 * @Primary 默认SqlSessionFactory
	 */
	@Bean(name = "zhilianSessionFactory")
	public SqlSessionFactory mysqlSqlSessionFactory(@Qualifier("zhilianDataSource") DataSource datasource)
			throws Exception {
		SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
		bean.setDataSource(datasource);
		// mybatis扫描xml所在位置
		bean.setMapperLocations(
				new PathMatchingResourcePatternResolver().getResources("classpath*:zhilianMapper/*.xml"));
		// 分页插件
//		Interceptor interceptor = new PageInterceptor();
		Properties properties = new Properties();
		// 数据库
		properties.setProperty("helperDialect", "mysql");
//        //是否将参数offset作为PageNum使用
//        properties.setProperty("offsetAsPageNum", "true");
//        //是否进行count查询
//        properties.setProperty("rowBoundsWithCount", "true");
		// 是否分页合理化
//		properties.setProperty("reasonable", "true");
//		interceptor.setProperties(properties);
//		bean.setPlugins(new Interceptor[] { interceptor });
		return bean.getObject();
	}

	@Bean("zhilianTemplate")
	public SqlSessionTemplate mysqlSqlSessionTemplate(
			@Qualifier("zhilianSessionFactory") SqlSessionFactory sqlSessionFactory) {
		return new SqlSessionTemplate(sqlSessionFactory);
	}

}

springboot hikari连接池配置多数据源 springboot配置多个连接池_数据源_02

这里要注意两个数据源的区别第一个数据源,@primary注解只能出现在一个数据源的配置类里面,还有就是@MapperScan(basePackages = “com.***.***.dao.zhilianMapper”, sqlSessionFactoryRef = “zhilianSessionFactory”),

!!!注意,两个数据源是不同的扫描路径,在使用的时候注入哪个包下的mapper就是使用的哪个数据源 !!!

springboot hikari连接池配置多数据源 springboot配置多个连接池_java_03

3.关闭springboot默认自动加载数据源

package com.***.***;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration;

@SpringBootApplication(exclude = {MongoAutoConfiguration.class,MongoDataAutoConfiguration.class,DataSourceAutoConfiguration.class})
//@EnableScheduling
@MapperScan("com.***.***.dao.mapper")
public class ***Application {
	public static void main(String[] args) {
		SpringApplication.run(***Application.class, args);
	}
}
关闭数据源自动装配

springboot hikari连接池配置多数据源 springboot配置多个连接池_java_04

这个项目中还设置了mongo多数据源,所以也一起关闭了

4.不同数据源的mapper调用

springboot hikari连接池配置多数据源 springboot配置多个连接池_数据源_05


直接注入即可

结束!以上配置类中临时没有用到分页插件,所以注释掉了,项目中集成了mybatis所以配置类中注意使用了SqlSessionFactory