一订咸、簡述
配置多數(shù)據(jù)源意思就是在一個(gè)項(xiàng)目中使用多個(gè)數(shù)據(jù)庫超营,在項(xiàng)目使用中可以不用手動切換數(shù)據(jù)庫來實(shí)現(xiàn)不同數(shù)據(jù)庫的數(shù)據(jù)獲取和更新协屡。
源碼地址: https://github.com/hanguilin/boot-security
項(xiàng)目環(huán)境: SpringBoot 2.1.9宫蛆、Spring Data Jpa
項(xiàng)目文件夾:
二赊抖、配置
application.properties
spring.datasource.primary.driver-class-name 數(shù)據(jù)庫驅(qū)動包
spring.datasource.primary.jdbc-url 數(shù)據(jù)庫連接
spring.datasource.primary.username 用戶名
spring.datasource.primary.password 密碼
數(shù)據(jù)庫配置別名可自定義统倒,此處一級庫為primmary。二級數(shù)據(jù)庫配置同上熏迹,別名為secondary檐薯。
hikara為數(shù)據(jù)庫連接池的配置,同類產(chǎn)品還有druid注暗。
server.port=8080
##########一級數(shù)據(jù)庫配置##########
spring.datasource.primary.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.primary.jdbc-url=jdbc:mysql://localhost:3306/primary_db?autoReconnect=true&useUnicode=true&useSSL=false
spring.datasource.primary.username=root
spring.datasource.primary.password=****
#最大連接數(shù)
spring.datasource.primary.hikari.maximum-pool-size=20
#連接超時(shí)毫秒
spring.datasource.primary.hikari.connection-timeout=60000
#空閑的連接的生命時(shí)長毫秒
spring.datasource.primary.hikari.idle-timeout=60000
#連接的生命時(shí)長毫秒
spring.datasource.primary.hikari.max-lifetime=60000
#驗(yàn)證連接有效性毫秒
spring.datasource.primary.hikari.validation-timeout=3000
#登錄超時(shí)毫秒
spring.datasource.primary.hikari.login-timeout=5
##########一級數(shù)據(jù)庫配置##########
##########二級數(shù)據(jù)庫配置##########
spring.datasource.secondary.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.secondary.jdbc-url=jdbc:mysql://localhost:3306/secondary_db?autoReconnect=true&useUnicode=true
spring.datasource.secondary.username=root
spring.datasource.secondary.password=****
#最大連接數(shù)
spring.datasource.secondary.hikari.maximum-pool-size=20
#連接超時(shí)毫秒
spring.datasource.secondary.hikari.connection-timeout=60000
#空閑的連接的生命時(shí)長毫秒
spring.datasource.secondary.hikari.idle-timeout=60000
#連接的生命時(shí)長毫秒
spring.datasource.secondary.hikari.max-lifetime=60000
#驗(yàn)證連接有效性毫秒
spring.datasource.secondary.hikari.validation-timeout=3000
#登錄超時(shí)毫秒
spring.datasource.secondary.hikari.login-timeout=5
##########二級數(shù)據(jù)庫配置##########
##########hibernate配置##########
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.hbm2ddl.auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
##########hibernate配置##########
DataSourcesConfig.java
- @Bean(name = "primaryDataSource")
將該返回對象交由Spring管理,bean名稱為primaryDataSource墓猎。
- @Qualifier("primaryDataSource")
根據(jù)名稱將bean注入到對象捆昏。
- @Primary
自動裝配時(shí)當(dāng)出現(xiàn)多個(gè)Bean候選者時(shí),被注解為@Primary的Bean將作為首選者毙沾,否則將拋出異常骗卜。
- @ConfigurationProperties(prefix="spring.datasource.primary")
將前綴為spring.datasource.primary的配置注入到對應(yīng)名稱的屬性字段中。
此類作用為生成兩級DataSource,交由Spring管理寇仓,方便后續(xù)從Spring中調(diào)用举户。
package com.spring.security.config.datasource;
import javax.sql.DataSource;
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 com.zaxxer.hikari.HikariDataSource;
@Configuration
public class DataSourcesConfig {
@Bean(name = "primaryDataSource")
@Qualifier("primaryDataSource")
@Primary
@ConfigurationProperties(prefix="spring.datasource.primary")
public DataSource primaryDataSource() {
return DataSourceBuilder.create()
.type(HikariDataSource.class)
.build();
}
@Bean(name = "secondaryDataSource")
@Qualifier("secondaryDataSource")
@ConfigurationProperties(prefix="spring.datasource.secondary")
public DataSource secondaryDataSource() {
return DataSourceBuilder.create()
.type(HikariDataSource.class)
.build();
}
}
PrimaryConfig.java
- @Configuration
在Spring中注冊成bean
- @EnableTransactionManagement
開啟事務(wù)管理
@EnableJpaRepositories(
entityManagerFactoryRef="entityManagerFactoryPrimary",
transactionManagerRef="transactionManagerPrimary",
basePackages= { "com.spring.security.dao.primary" })
- @EnableJpaRepositories
注解用于Srping JPA的代碼配置,用于取代xml形式的配置文件
- entityManagerFactoryRef
實(shí)體管理工廠遍烦,下文代碼中配置基礎(chǔ)包為com.spring.security.entity.primary
- transactionManagerRef
事務(wù)管理
- basePackages
持久層基礎(chǔ)包掃描俭嘁,此處配置為com.spring.security.dao.primary
上述兩個(gè)包的配置,意為一級數(shù)據(jù)庫的實(shí)體和dao蹭接口分別所處的位置服猪。當(dāng)jpa進(jìn)行實(shí)體映射時(shí)供填,對應(yīng)包下面的實(shí)體會映射到不通的數(shù)據(jù)庫。dao層接口也會隨之切換罢猪。
package com.spring.security.config.datasource;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.sql.DataSource;
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;
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef="entityManagerFactoryPrimary",
transactionManagerRef="transactionManagerPrimary",
basePackages= { "com.spring.security.dao.primary" }) //設(shè)置Repository所在位置
public class PrimaryConfig {
@Autowired
@Qualifier("primaryDataSource")
private DataSource primaryDataSource;
@Autowired(required=false)
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) {
return builder
.dataSource(primaryDataSource)
.properties(getVendorProperties())
.packages("com.spring.security.entity.primary") //設(shè)置實(shí)體類所在位置
.persistenceUnit("primaryPersistenceUnit")
.build();
}
private Map<String, Object> getVendorProperties() {
return jpaProperties.getHibernateProperties(new HibernateSettings());
}
@Primary
@Bean(name = "transactionManagerPrimary")
public PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder) {
return new JpaTransactionManager(entityManagerFactoryPrimary(builder).getObject());
}
}
SecondaryConfig.java
package com.spring.security.config.datasource;
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;
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef="entityManagerFactorySecondary",
transactionManagerRef="transactionManagerSecondary",
basePackages= { "com.spring.security.dao.secondary" }) //設(shè)置Repository所在位置
public class SecondaryConfig {
@Autowired
private JpaProperties jpaProperties;
@Autowired
@Qualifier("secondaryDataSource")
private DataSource secondaryDataSource;
@Bean(name = "entityManagerSecondary")
public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
return entityManagerFactorySecondary(builder).getObject().createEntityManager();
}
@Bean(name = "entityManagerFactorySecondary")
public LocalContainerEntityManagerFactoryBean entityManagerFactorySecondary (EntityManagerFactoryBuilder builder) {
return builder
.dataSource(secondaryDataSource)
.properties(getVendorProperties())
.packages("com.spring.security.entity.secondary") //設(shè)置實(shí)體類所在位置
.persistenceUnit("secondaryPersistenceUnit")
.build();
}
private Map<String, Object> getVendorProperties() {
return jpaProperties.getHibernateProperties(new HibernateSettings());
}
@Bean(name = "transactionManagerSecondary")
PlatformTransactionManager transactionManagerSecondary(EntityManagerFactoryBuilder builder) {
return new JpaTransactionManager(entityManagerFactorySecondary(builder).getObject());
}
}
如果需要擴(kuò)展更多數(shù)據(jù)庫近她,可以根據(jù)上述配置自行增加。