SpringBoot2.x配置多數(shù)據(jù)源方式
本文章主要實(shí)現(xiàn)配置多數(shù)據(jù)源,適用springBoot2.x版本,2.0以下版本可以參考我的博客 springBoot整合Hakari數(shù)據(jù)庫連接池
一、前言以及搭建環(huán)境
springBoot1.x版本的數(shù)據(jù)庫連接池不是Hakari,在springBoot2.0版本以后才默認(rèn)是Hakari,現(xiàn)在很多druid數(shù)據(jù)庫連接池,但是他們的性能我并沒有進(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ù)庫配置文件
#第一個(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ù)庫配置文件可以都放在application.properties文件中
<2>springBoot2.x使用JDBC連接數(shù)據(jù)庫需要將url改為jdbc-url
<3>添加JDBC驅(qū)動(dòng)名稱由原來的com.mysql.jdbc.Driver改為 com.mysql.cj.jdbc.Driver
<4>配置多數(shù)據(jù)源和配置單數(shù)據(jù)源沒有什么區(qū)別,使用primary和secondary來標(biāo)注不同的數(shù)據(jù)源;(名字也可以換掉)
四、代碼
1. DataSourceConfig.java
/** * @Create Date: 2017年8月13日下午11:59:49 * @Version: V1.00 * @Author: 追到烏云的盡頭找太陽 */ @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ù)庫連接池創(chuàng)建中......."); return DataSourceBuilder.create().build(); } @Bean(name = "secondaryDataSource") @Qualifier("secondaryDataSource") @ConfigurationProperties(prefix="spring.datasource.secondary") public DataSource secondaryDataSource() { logger.info("第二個(gè)數(shù)據(jù)庫連接池創(chuàng)建中......"); return DataSourceBuilder.create().build(); } }
說明:
<1>@PropertySource(“classpath:datasource.properties”)是用來獲取數(shù)據(jù)庫配置文件的,如果在application.properties中配置的話不需要此注解(PropertySource注解還是很好用的 )
<2> @ConfigurationProperties(prefix=“spring.datasource.primary” )是用來獲取第一個(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: 追到烏云的盡頭找太陽 */ @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:追到烏云的盡頭找太陽 */ @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開發(fā)學(xué)習(xí)之Bean的生命周期詳解
從創(chuàng)建到消亡的完整過程,例如人從出生到死亡的整個(gè)過程就是一個(gè)生命周期。本文將通過示例為大家詳細(xì)講講Bean的生命周期,感興趣的可以學(xué)習(xí)一下2022-06-06MyBatis-Plus實(shí)現(xiàn)邏輯刪除功能解析
這篇文章主要介紹了MyBatis-Plus實(shí)現(xiàn)邏輯刪除功能解析,有時(shí)候并不需要真正的刪除數(shù)據(jù),而是想邏輯刪除,方便數(shù)據(jù)恢復(fù),MyBatis-Plus可以很方便的實(shí)現(xiàn)邏輯刪除的功能,需要的朋友可以參考下2023-11-11Spring IOC推導(dǎo)與DI構(gòu)造器注入超詳細(xì)講解
這篇文章主要介紹了Spring IOC推導(dǎo)與DI構(gòu)造器注入,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2023-02-02從內(nèi)存地址解析Java的static關(guān)鍵字的作用
這篇文章主要介紹了從內(nèi)存地址解析Java的static關(guān)鍵字的作用,包括靜態(tài)成員變量和靜態(tài)方法等重要內(nèi)容,需要的朋友可以參考下2015-10-10java定時(shí)任務(wù)Timer和TimerTask使用詳解
這篇文章主要為大家詳細(xì)介紹了java定時(shí)任務(wù)Timer和TimerTask使用方法,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-02-02SpringBoot中使用EasyExcel并行導(dǎo)出多個(gè)excel文件并壓縮zip后下載的代碼詳解
SpringBoot的同步導(dǎo)出方式中,服務(wù)器會(huì)阻塞直到Excel文件生成完畢,在處理大量數(shù)據(jù)的導(dǎo)出功能,本文給大家介紹了SpringBoot中使用EasyExcel并行導(dǎo)出多個(gè)excel文件并壓縮zip后下載,需要的朋友可以參考下2024-09-09詳解Java線程池如何統(tǒng)計(jì)線程空閑時(shí)間
這篇文章主要和大家分享一個(gè)面試題:Java線程池是怎么統(tǒng)計(jì)線程空閑時(shí)間?文中的示例代碼講解詳細(xì),對(duì)我們掌握J(rèn)ava有一定幫助,需要的可以參考一下2022-11-11