SpringBoot2.x配置多數(shù)據(jù)源方式
本文章主要實(shí)現(xiàn)配置多數(shù)據(jù)源,適用springBoot2.x版本,2.0以下版本可以參考我的博客 springBoot整合Hakari數(shù)據(jù)庫(kù)連接池
一、前言以及搭建環(huán)境
springBoot1.x版本的數(shù)據(jù)庫(kù)連接池不是Hakari,在springBoot2.0版本以后才默認(rèn)是Hakari,現(xiàn)在很多druid數(shù)據(jù)庫(kù)連接池,但是他們的性能我并沒有進(jìn)行比較,所以還是使用Hakari連接池,springBoot2.x配置數(shù)據(jù)源和以前有少許不同,將會(huì)重點(diǎn)標(biāo)出不同。
環(huán)境:springBoot2.1.4 jdk1.8 maven mysql
二、項(xiàng)目結(jié)構(gòu)
我的項(xiàng)目結(jié)構(gòu)如下圖:

三、配置文件
1.maven pom.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.zgx</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Communication</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
<exclusions>
<exclusion>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jdbc</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- spring boot 內(nèi)置tomcat -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<!-- <scope>runtime</scope> -->
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2.datasources.properties數(shù)據(jù)庫(kù)配置文件
#第一個(gè)數(shù)據(jù)源 spring.datasource.primary.jdbc-url: jdbc:mysql://127。0.0.1:3306/communication?useUnicode=true&characterEncoding=utf-8 spring.datasource.primary.driver-class-name: com.mysql.cj.jdbc.Driver spring.datasource.primary.username=root spring.datasource.primary.password=123456 #第二個(gè)數(shù)據(jù)源 spring.datasource.secondary.jdbc-url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8 spring.datasource.secondary.driver-class-name: com.mysql.cj.jdbc.Driver spring.datasource.secondary.username=root spring.datasource.secondary.password=123456 # 下面為連接池的補(bǔ)充設(shè)置,應(yīng)用到上面所有數(shù)據(jù)源中 #自動(dòng)提交 spring.datasource.default-auto-commit=true #指定updates是否自動(dòng)提交 spring.datasource.auto-commit=true spring.jpa.show-sql = true spring.datasource.maximum-pool-size=100 spring.datasource.max-idle=10 spring.datasource.max-wait=10000 spring.datasource.min-idle=5 spring.datasource.initial-size=5 spring.datasource.validation-query=SELECT 1 spring.datasource.test-on-borrow=false spring.datasource.test-while-idle=true # 配置間隔多久才進(jìn)行一次檢測(cè),檢測(cè)需要關(guān)閉的空閑連接,單位是毫秒 spring.datasource.time-between-eviction-runs-millis=18800 # 配置一個(gè)連接在池中最小生存的時(shí)間,單位是毫秒 spring.datasource.minEvictableIdleTimeMillis=300000 # Hibernate ddl auto (create, create-drop, update) spring.jpa.hibernate.ddl-auto=update #spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect spring.jpa.hibernate.naming_strategy=org.hibernate.cfg.ImprovedNamingStrategy #spring.jpa.database=org.hibernate.dialect.MySQL5InnoDBDialect spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
說明
<1> 數(shù)據(jù)庫(kù)配置文件可以都放在application.properties文件中
<2>springBoot2.x使用JDBC連接數(shù)據(jù)庫(kù)需要將url改為jdbc-url
<3>添加JDBC驅(qū)動(dòng)名稱由原來(lái)的com.mysql.jdbc.Driver改為 com.mysql.cj.jdbc.Driver
<4>配置多數(shù)據(jù)源和配置單數(shù)據(jù)源沒有什么區(qū)別,使用primary和secondary來(lái)標(biāo)注不同的數(shù)據(jù)源;(名字也可以換掉)
四、代碼
1. DataSourceConfig.java
/**
* @Create Date: 2017年8月13日下午11:59:49
* @Version: V1.00
* @Author: 追到烏云的盡頭找太陽(yáng)
*/
@Configuration
@PropertySource("classpath:datasource.properties")
public class DataSourceConfig {
private Logger logger = LoggerFactory.getLogger(DataSourceConfig.class);
@Bean(name = "primaryDataSource")
@Primary
@Qualifier("primaryDataSource")
@ConfigurationProperties(prefix="spring.datasource.primary" )
public DataSource primaryDataSource() {
logger.info("第一個(gè)數(shù)據(jù)庫(kù)連接池創(chuàng)建中.......");
return DataSourceBuilder.create().build();
}
@Bean(name = "secondaryDataSource")
@Qualifier("secondaryDataSource")
@ConfigurationProperties(prefix="spring.datasource.secondary")
public DataSource secondaryDataSource() {
logger.info("第二個(gè)數(shù)據(jù)庫(kù)連接池創(chuàng)建中......");
return DataSourceBuilder.create().build();
}
}
說明:
<1>@PropertySource(“classpath:datasource.properties”)是用來(lái)獲取數(shù)據(jù)庫(kù)配置文件的,如果在application.properties中配置的話不需要此注解(PropertySource注解還是很好用的 )
<2> @ConfigurationProperties(prefix=“spring.datasource.primary” )是用來(lái)獲取第一個(gè)數(shù)據(jù)源的配置參數(shù)
2. PrimaryDataSouceConfig.java
/**
* <p>Company: B505信息技術(shù)研究所 </p>
* @Description: 第一個(gè)數(shù)據(jù)源的配置類
* @Create Date: 2017年5月11日下午9:22:12
* @Version: V1.00
* @Author: 追到烏云的盡頭找太陽(yáng)
*/
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef="entityManagerFactoryPrimary",
transactionManagerRef="transactionManagerPrimary",
basePackages= { "com.zgx.dao" }) // 設(shè)置Repository所在位置
public class PrimaryDataSouceConfig {
@Autowired @Qualifier("primaryDataSource")
private DataSource primaryDataSource;
@Autowired
private HibernateProperties hibernateProperties;
@Autowired
private JpaProperties jpaProperties;
@Primary
@Bean(name = "entityManagerPrimary")
@ConfigurationProperties(prefix="spring.datasourse.primary")
public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
return entityManagerFactoryPrimary(builder).getObject().createEntityManager();
}
@Primary
@Bean(name = "entityManagerFactoryPrimary")
public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary (EntityManagerFactoryBuilder builder) {
//springBoot2.x這樣寫就行了
Map<String, Object> propertiesMap= hibernateProperties.determineHibernateProperties(jpaProperties.getProperties(), new HibernateSettings());
return builder
.dataSource(primaryDataSource)
.properties(propertiesMap)
.packages("com.zgx.entity") // 設(shè)置實(shí)體類所在位置
.persistenceUnit("primaryPersistenceUnit")
.build();
}
/* // 此方法在springBoot2.x以上版本不適合了
private Map<String, String> getVendorProperties(Datasorce datasorce) {
return jpaProperties.getHibernateProperties(datasorce);
}*/
@Primary
@Bean(name = "transactionManagerPrimary")
public PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder) {
return new JpaTransactionManager(entityManagerFactoryPrimary(builder).getObject());
}
}
3.SecondDataSourceConfig.java
/**
* <p>Company: B505信息技術(shù)研究所 </p>
* @Description: 第二個(gè)數(shù)據(jù)源的配置類(entity和Dao所在位置)
* @Create Date: 2017年5月11日下午9:22:12
* @Version: V1.00
* @Author:追到烏云的盡頭找太陽(yáng)
*/
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef="entityManagerFactorySecondary",
transactionManagerRef="transactionManagerSecondary",
basePackages= { "com.zgx.test.dao" }) // 設(shè)置Repository所在位置
public class SecondaryDataSouceConfig {
@Autowired @Qualifier("secondaryDataSource")
private DataSource secondaryDataSource;
@Autowired
private HibernateProperties hibernateProperties;
@Autowired
private JpaProperties jpaProperties;
@Primary
@Bean(name = "entityManagerSecondary")
@ConfigurationProperties(prefix="spring.datasourse.secondary")
public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
return entityManagerFactoryPrimary(builder).getObject().createEntityManager();
}
@Primary
@Bean(name = "entityManagerFactorySecondary")
public LocalContainerEntityManagerFactoryBean entityManagerFactorySecondary (EntityManagerFactoryBuilder builder) {
Map<String, Object> propertiesMap= hibernateProperties.determineHibernateProperties(jpaProperties.getProperties(), new HibernateSettings());
return builder
.dataSource(secondaryDataSource)
.properties(propertiesMap)
.packages("com.zgx.test.entity") // 設(shè)置實(shí)體類所在位置
.persistenceUnit("secondaryPersistenceUnit")
.build();
}
/* // 此方法在springBoot2.1以上版本不適合了
private Map<String, String> getVendorProperties() {
return jpaProperties.getHibernateProperties(new HibernateProperties());
}*/
@Primary
@Bean(name = "transactionManagerSecondary")
public PlatformTransactionManager transactionManagerSecondary(EntityManagerFactoryBuilder builder) {
return new JpaTransactionManager(entityManagerFactorySecondary(builder).getObject());
}
}
}
說明:不管是第一個(gè)數(shù)據(jù)源還是第二個(gè)數(shù)據(jù)源都需要設(shè)置實(shí)體類以及dao層;
<1> basePackages= { “com.zgx.dao” }) // 設(shè)置Repository所在位置
<2> .packages(“com.zgx.test.entity”) // 設(shè)置實(shí)體類所在位置
這兩個(gè)一定要按照自己的實(shí)際情況進(jìn)行修改;
private Map<String, String> getVendorProperties() {
return jpaProperties.getHibernateProperties(new HibernateProperties());
}方法在springBoot2.x版本已經(jīng)不再適用,可以參照上面代碼修改即可,SpringBoot1.x和2.x配置數(shù)據(jù)源主要是這里發(fā)生里變化;
五、最后
在使用上述maven依賴時(shí)會(huì)發(fā)生一個(gè)mysql時(shí)區(qū)錯(cuò)誤
這是由于版本問題,此問題我已經(jīng)在我的上一篇博客進(jìn)行了總結(jié):
mysql 時(shí)區(qū)問題原因以及方法總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
java實(shí)現(xiàn)讀取txt文件中的內(nèi)容
本文通過一個(gè)具體的例子向大家展示了如何使用java實(shí)現(xiàn)讀取TXT文件里的內(nèi)容的方法以及思路,有需要的小伙伴可以參考下2016-03-03
Java 8系列之Stream中萬(wàn)能的reduce用法說明
這篇文章主要介紹了Java 8系列之Stream中萬(wàn)能的reduce用法說明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來(lái)看看吧2020-08-08
Maven遠(yuǎn)程倉(cāng)庫(kù)地址修改實(shí)現(xiàn)解析
這篇文章主要介紹了Maven遠(yuǎn)程倉(cāng)庫(kù)地址修改實(shí)現(xiàn)解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-11-11
Java日常練習(xí)題,每天進(jìn)步一點(diǎn)點(diǎn)(61)
下面小編就為大家?guī)?lái)一篇Java基礎(chǔ)的幾道練習(xí)題(分享)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來(lái)看看吧,希望可以幫到你2021-08-08
基于Spring Boot 的小區(qū)人臉識(shí)別與出入記錄管理系統(tǒng)功能
文章介紹基于SpringBoot框架與百度AI人臉識(shí)別API的小區(qū)出入管理系統(tǒng),實(shí)現(xiàn)自動(dòng)識(shí)別、記錄及查詢功能,涵蓋技術(shù)選型、數(shù)據(jù)模型設(shè)計(jì)、接口開發(fā)與系統(tǒng)優(yōu)化方案,為智慧社區(qū)提供高效安全管理工具,感興趣的朋友跟隨小編一起看看吧2025-08-08
Spring深入分析講解BeanUtils的實(shí)現(xiàn)
java知識(shí)體系統(tǒng)有很多數(shù)據(jù)實(shí)體,比較常用的DTO、BO、DO、VO等,其他類似POJO概念太老了現(xiàn)在基本廢棄掉了,本篇幅直接忽略,對(duì)于這幾種數(shù)據(jù)實(shí)體各自代表的含義和應(yīng)用場(chǎng)景先做一下簡(jiǎn)單描述和分析2022-06-06
SpringBoot2.6.x 與 Swagger3 兼容問題及解決方法
文章介紹了Spring Boot 2.6.x與Swagger 3兼容性問題的解決方法,如果項(xiàng)目中未引入spring-boot-starter-actuator,則在yml文件中加入相關(guān)配置,反之,需要添加其他配置,感興趣的朋友一起看看吧2025-03-03
JFreeChart動(dòng)態(tài)畫折線圖的方法
這篇文章主要為大家詳細(xì)介紹了JFreeChart動(dòng)態(tài)畫折線圖的方法,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-06-06

