1、配置數據庫的鏈接屬性java
lmysql
package com.example.song.config;web
import java.sql.SQLException;spring
import javax.sql.DataSource;sql
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;數據庫
import com.alibaba.druid.pool.DruidDataSource;app
/**
* @ClassName: DruidDBConfig
* @Description: 設置數據庫的鏈接屬性
* @author songyunfei
* @date 2018年6月26日 下午3:51:53
*
*/
@ServletComponentScan
@Configuration
public class DruidDBConfig {
private Logger logger=LoggerFactory.getLogger(DruidDBConfig.class);
@Value("${spring.datasource.primary.url}")
private String dbUrl1;
@Value("${spring.datasource.primary.username}")
private String username1;
@Value("${spring.datasource.primary.password}")
private String password1;
@Value("${spring.datasource.secondary.url}")
private String dbUrl2;
@Value("${spring.datasource.secondary.username}")
private String username2;
@Value("${spring.datasource.secondary.password}")
private String password2;
@Value("com.mysql.jdbc.Driver")
private String driverClassName;
@Value("5")
private int initialSize;
@Value("5")
private int minIdle;
@Value("20")
private int maxActive;
@Value("60000")
private int maxWait;
/**
* 配置間隔多久才進行一次檢測,檢測須要關閉的空閒鏈接,單位是毫秒
*/
@Value("60000")
private int timeBetweenEvictionRunsMillis;dom
/**
* 配置一個鏈接在池中最小生存的時間,單位是毫秒
*/
@Value("300000")
private int minEvictableIdleTimeMillis;
@Value("SELECT 1 FROM DUAL")
private String validationQuery;
@Value("true")
private boolean testWhileIdle;
@Value("false")
private boolean testOnBorrow;
@Value("false")
private boolean testOnReturn;
/**
* 打開PSCache,而且指定每一個鏈接上PSCache的大小
*/
@Value("true")
private boolean poolPreparedStatements;
@Value("20")
private int maxPoolPreparedStatementPerConnectionSize;
/**
* 配置監控統計攔截的filters,去掉後監控界面sql沒法統計,'wall'用於防火牆
*/
@Value("stat,wall,log4j")
private String filters;
/**
* 經過connectProperties屬性來打開mergeSql功能;慢SQL記錄
*/
@Value("druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500")
private String connectionProperties;
@Bean(name = "primaryDataSource")
@Qualifier("primaryDataSource")
public DataSource dataSource() {
return getDruidDataSource(username1, password1, dbUrl1);
}
@Bean(name = "secondaryDataSource")
@Qualifier("secondaryDataSource") //設置注入bean的名稱spring容器在注入經過byname 而不是bytype
@Primary
public DataSource secondaryDataSource() {
return getDruidDataSource(username2, password2, dbUrl2);
}
private DruidDataSource getDruidDataSource(String username, String password, String url) {
DruidDataSource datasource = new DruidDataSource();
datasource.setUrl(url);
datasource.setUsername(username);
datasource.setPassword(password);
datasource.setDriverClassName(driverClassName);
//configuration
datasource.setInitialSize(initialSize);
datasource.setMinIdle(minIdle);
datasource.setMaxActive(maxActive);
datasource.setMaxWait(maxWait);
datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
datasource.setValidationQuery(validationQuery);
datasource.setTestWhileIdle(testWhileIdle);
datasource.setTestOnBorrow(testOnBorrow);
datasource.setTestOnReturn(testOnReturn);
datasource.setPoolPreparedStatements(poolPreparedStatements);
datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
try {
datasource.setFilters(filters);
} catch (SQLException e) {
logger.error("druid configuration initialization filter : {0}", e);
}
datasource.setConnectionProperties(connectionProperties);
return datasource;
}
}ui
2、主數據源(第一數據源)的配置url
package com.example.song.config;
import java.util.Map;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.sql.DataSource;
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.example.song.mapper.primary"})
public class PrimaryConfig {
@Resource
@Qualifier("primaryDataSource")
private DataSource primaryDataSource;
@Primary
@Bean(name = "entityManagerPrimary")
public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
return entityManagerFactoryPrimary(builder).getObject().createEntityManager();
}
@Resource
private JpaProperties jpaProperties;
private Map<String, Object> getVendorProperties() {
return jpaProperties.getHibernateProperties(new HibernateSettings());
}
/**
* 設置實體類的位置
*/
@Primary
@Bean(name="entityManagerFactoryPrimary")
public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary(EntityManagerFactoryBuilder builder){
return builder.dataSource(primaryDataSource)
.packages("com.example.song.domain.primary")
.persistenceUnit("primaryPersistenceUnit")
.properties(getVendorProperties())
.build();
}
@Primary
@Bean(name="transactionManagerPrimary")
public PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder){
return new JpaTransactionManager(entityManagerFactoryPrimary(builder).getObject());
}
}
3、第二數據源的配置
package com.example.song.config;
import java.util.Map;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.sql.DataSource;
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;
/**
*
* @ClassName: SecondaryDataSource
* @Description: 第二數據源的配置
* @author songyunfei
* @date 2018年6月26日 下午4:13:11
*
*/
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories( entityManagerFactoryRef = "entityManagerFactorySecondary",
transactionManagerRef = "transactionManagerSecondary",
basePackages = {"com.example.song.mapper.scondary"})
public class SecondaryConfig {
@Resource
@Qualifier("secondaryDataSource")
private DataSource secondaryDataSource;
@Bean(name = "entityManagerSecondary")
public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
return entityManagerFactorySecondary(builder).getObject().createEntityManager();
}
@Resource
private JpaProperties jpaProperties;
private Map<String, Object> getVendorProperties() {
return jpaProperties.getHibernateProperties(new HibernateSettings());
}
/**
* 設置實體類的位置
*/
@Bean(name="entityManagerFactorySecondary")
public LocalContainerEntityManagerFactoryBean entityManagerFactorySecondary(EntityManagerFactoryBuilder builder){
return builder.dataSource(secondaryDataSource)
.packages("com.example.song.domain.secondary")
.persistenceUnit("secondaryPersistenceUnit")
.properties(getVendorProperties())
.build();
}
@Bean(name="transactionManagerSecondary")
public PlatformTransactionManager transactionManagerSecondary(EntityManagerFactoryBuilder builder){
return new JpaTransactionManager(entityManagerFactorySecondary(builder).getObject());
}
}
總結:以上代碼也是從網上其餘的網友哪裏copy過來,本身改了點配置,很是感謝其餘網友的貢獻
程序如今正常運行,可是仍是有問題如今不是很清楚
①若是一個service中調用了兩個數據源,那麼事物怎麼控制,本身寫的demo中發現不一樣的數據源,一個數據源出錯,仍是會回滾的
②在實際的環境中,多數據源的使用會有哪些問題,目前咱們公司尚未使用到多數據源