Spring Boot 2.0.X 多數據源及鏈接池配置

1、單數據源java

咱們在使用Spring Boot配置單數據源的時候很簡單,只要在配置文件中加上基本的數據庫鏈接信息和鏈接池配置信息就能夠,一般狀況下不須要指定driver-class-name,Spring Boot能夠從大多數數據庫的url中推斷出驅動類型mysql

# 鏈接配置
spring.datasource.url=jdbc:mysql://localhost:part/test?characterEncoding=utf-8
spring.datasource.username=****
spring.datasource.password=****
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

# 鏈接池配置
spring.datasource.hikari.pool-name=HikariPool
spring.datasource.hikari.minimum-idle=5
spring.datasource.hikari.maximum-pool-size=10
spring.datasource.hikari.connection-timeout=30000
spring.datasource.hikari.idle-timeout=600000
spring.datasource.hikari.max-lifetime=1800000

# jpa相關配置
spring.jpa.show-sql = true
spring.jpa.properties.hibernate.format_sql = true
spring.jpa.properties.hibernate.max_fetch_depth = 1
spring.jpa.hibernate.ddl-auto = update
# SpringBoot2.0之後須要指定方言才能使用InnoDB引擎
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.open-in-view=false

Spring Boot 2.0之後默認使用 HikariCP 鏈接池,2.0之前默認使用的是 Tomcat 鏈接池,若是想在2.0之前使用 HikariCP 鏈接池,能夠在maven中手動引入HikariCP 鏈接池依賴git

<dependency>
       <groupId>com.zaxxer</groupId>
       <artifactId>HikariCP</artifactId>
       <version>2.7.8</version>
</dependency>

並在配置文件中添加以下配置便可github

spring.datasource.type=com.zaxxer.hikari.HikariDataSource

2、多數據源spring

1.配置多數據源鏈接配置,根據前綴來區分,並配置對應鏈接池信息sql

#主數據庫
spring.datasource.primary.jdbc-url=jdbc:mysql://127.0.0.1:3306/test1?characterEncoding=utf-8
spring.datasource.primary.username=root
spring.datasource.primary.password=mysql
spring.datasource.primary.driver-class-name = com.mysql.jdbc.Driver
#從數據庫
spring.datasource.secondary.jdbc-url=jdbc:mysql://127.0.0.1:3306/test2?characterEncoding=utf-8
spring.datasource.secondary.username=root
spring.datasource.secondary.password=mysql
spring.datasource.secondary.driver-class-name = com.mysql.jdbc.Driver

##  Hikari 鏈接池配置 ------ 詳細配置請訪問:https://github.com/brettwooldridge/HikariCP
## 鏈接池名稱
spring.datasource.primary.pool-name=HikariPool-1
## 最小空閒鏈接數量,默認是10
spring.datasource.primary.minimum-idle=5
## 鏈接池最大鏈接數,默認是10
spring.datasource.primary.maximum-pool-size=10
## 空閒鏈接存活最大時間,默認600000(10分鐘)
spring.datasource.primary.idle-timeout=600000
## 此屬性控制池中鏈接的最長生命週期,值0表示無限生命週期,默認1800000即30分鐘
spring.datasource.primary.max-lifetime=1800000
## 數據庫鏈接超時時間,默認30秒,即30000
spring.datasource.primary.connection-timeout=30000

spring.datasource.secondary.pool-name=HikariPool-2
spring.datasource.secondary.minimum-idle=5
spring.datasource.secondary.maximum-pool-size=10
spring.datasource.secondary.idle-timeout=600000
spring.datasource.secondary.max-lifetime=1800000
spring.datasource.secondary.connection-timeout=30000

# jpa相關配置
spring.jpa.show-sql = true
spring.jpa.properties.hibernate.format_sql = true
spring.jpa.properties.hibernate.max_fetch_depth = 1
spring.jpa.hibernate.ddl-auto = update
# SpringBoot2.0之後須要指定方言才能使用InnoDB引擎
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.open-in-view=false

2.手動配置建立多個數據庫鏈接池,prefix配置屬性的前綴要與配置文件中的一致,實例化Bean交給Spring容器管理數據庫

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

import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
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 javax.sql.DataSource;

@Slf4j
@Configuration
public class DataSourceConfig {

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

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


    /**
     * 顯示數據庫鏈接池信息
     *
     * @param dataSource
     */
    public static void logDS(DataSource dataSource) {
        HikariDataSource hds = (HikariDataSource) dataSource;
        String info = "\n\n\tHikariCP鏈接池配置\n\t鏈接池名稱:" +
                hds.getPoolName() +
                "\n\t最小空閒鏈接數:" +
                hds.getMinimumIdle() +
                "\n\t最大鏈接數:" +
                hds.getMaximumPoolSize() +
                "\n\t鏈接超時時間:" +
                hds.getConnectionTimeout() +
                "ms\n\t空閒鏈接超時時間:" +
                hds.getIdleTimeout() +
                "ms\n\t鏈接最長生命週期:" +
                hds.getMaxLifetime() +
                "ms\n";
        log.info(info);
    }
}

3.對每一個鏈接池指定相對應的實體類和repository包路徑,添加實體管理、jpa屬性管理、事務管理配置。jpa屬性能夠在配置文件中統一配置,或者經過如如下 getVendorProperties 方法分開配置,尤爲在鏈接不一樣數據庫時。app

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.Map;

@Slf4j
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "entityManagerFactoryPrimary",
        transactionManagerRef = "transactionManagerPrimary",
        basePackages = {"com.***.***.repository.applet"}) //設置Repository所在位置
public class PrimaryConfig {

    @Autowired
    @Qualifier("primaryDataSource")
    private DataSource primaryDataSource;

    @Autowired
    private JpaProperties jpaProperties;

    @Primary
    @Bean(name = "entityManagerPrimary")
    public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
        return entityManagerFactoryPrimary(builder).getObject().createEntityManager();
    }

    @Primary
    @Bean(name = "entityManagerFactoryPrimary")
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary(EntityManagerFactoryBuilder builder) {
        DataSourceConfig.logDS(primaryDataSource);
        return builder
                .dataSource(primaryDataSource)
                .properties(getVendorProperties())
                .packages("com.***.***.model.applet") //設置實體類所在位置
                .persistenceUnit("primaryPersistenceUnit")
                .build();
    }

    /**
     * jpa properties
     *
     * @return
     */
    private Map<String, Object> getVendorProperties() {
        Map<String, Object> ret = jpaProperties.getHibernateProperties(new HibernateSettings());
        ret.put("hibernate.dialect", "org.hibernate.dialect.MySQL5InnoDBDialect");
        return ret;
    }

    @Primary
    @Bean(name = "transactionManagerPrimary")
    public PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactoryPrimary(builder).getObject());
    }
}

 

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.Map;

@Slf4j
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "entityManagerFactorySecondary",
        transactionManagerRef = "transactionManagerSecondary",
        basePackages = {"com.***.***.repository.master"}) //設置Repository所在位置
public class SecondaryConfig {

    @Autowired
    @Qualifier("secondaryDataSource")
    private DataSource secondaryDataSource;

    @Autowired
    private JpaProperties jpaProperties;

    @Bean(name = "entityManagerSecondary")
    public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
        return entityManagerFactorySecondary(builder).getObject().createEntityManager();
    }

    @Bean(name = "entityManagerFactorySecondary")
    public LocalContainerEntityManagerFactoryBean entityManagerFactorySecondary(EntityManagerFactoryBuilder builder) {
        DataSourceConfig.logDS(secondaryDataSource);
        return builder
                .dataSource(secondaryDataSource)
                .properties(getVendorProperties())
                .packages("com.***.***.model.master") //設置實體類所在位置
                .persistenceUnit("secondaryPersistenceUnit")
                .build();
    }

    /**
     * jpa properties
     *
     * @return
     */
    private Map<String, Object> getVendorProperties() {
        Map<String, Object> ret = jpaProperties.getHibernateProperties(new HibernateSettings());
        ret.put("hibernate.dialect", "org.hibernate.dialect.MySQL5InnoDBDialect");
        return ret;
    }

    @Bean(name = "transactionManagerSecondary")
    PlatformTransactionManager transactionManagerSecondary(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactorySecondary(builder).getObject());
    }
}

 至此Spring Boot 2.0配置多數據源就完成了,此方法也適用於其餘數據庫配置,而且能夠繼續添加數據源,只需修改或添加application.properties中的數據源配置便可。maven

相關文章
相關標籤/搜索