SpringBoot2.x配置多数据源方式
作者:喵喵@香菜
本文章主要实现配置多数据源,适用springBoot2.x版本,2.0以下版本可以参考我的博客 springBoot整合Hakari数据库连接池
一、前言以及搭建环境
springBoot1.x版本的数据库连接池不是Hakari,在springBoot2.0版本以后才默认是Hakari,现在很多druid数据库连接池,但是他们的性能我并没有进行比较,所以还是使用Hakari连接池,springBoot2.x配置数据源和以前有少许不同,将会重点标出不同。
环境:springBoot2.1.4 jdk1.8 maven mysql
二、项目结构
我的项目结构如下图:
三、配置文件
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 内置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数据库配置文件
#第一个数据源 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 #第二个数据源 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 # 下面为连接池的补充设置,应用到上面所有数据源中 #自动提交 spring.datasource.default-auto-commit=true #指定updates是否自动提交 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 # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 spring.datasource.time-between-eviction-runs-millis=18800 # 配置一个连接在池中最小生存的时间,单位是毫秒 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> 数据库配置文件可以都放在application.properties文件中
<2>springBoot2.x使用JDBC连接数据库需要将url改为jdbc-url
<3>添加JDBC驱动名称由原来的com.mysql.jdbc.Driver改为 com.mysql.cj.jdbc.Driver
<4>配置多数据源和配置单数据源没有什么区别,使用primary和secondary来标注不同的数据源;(名字也可以换掉)
四、代码
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("第一个数据库连接池创建中......."); return DataSourceBuilder.create().build(); } @Bean(name = "secondaryDataSource") @Qualifier("secondaryDataSource") @ConfigurationProperties(prefix="spring.datasource.secondary") public DataSource secondaryDataSource() { logger.info("第二个数据库连接池创建中......"); return DataSourceBuilder.create().build(); } }
说明:
<1>@PropertySource(“classpath:datasource.properties”)是用来获取数据库配置文件的,如果在application.properties中配置的话不需要此注解(PropertySource注解还是很好用的 )
<2> @ConfigurationProperties(prefix=“spring.datasource.primary” )是用来获取第一个数据源的配置参数
2. PrimaryDataSouceConfig.java
/** * <p>Company: B505信息技术研究所 </p> * @Description: 第一个数据源的配置类 * @Create Date: 2017年5月11日下午9:22:12 * @Version: V1.00 * @Author: 追到乌云的尽头找太阳 */ @Configuration @EnableTransactionManagement @EnableJpaRepositories( entityManagerFactoryRef="entityManagerFactoryPrimary", transactionManagerRef="transactionManagerPrimary", basePackages= { "com.zgx.dao" }) // 设置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") // 设置实体类所在位置 .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信息技术研究所 </p> * @Description: 第二个数据源的配置类(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" }) // 设置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") // 设置实体类所在位置 .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()); } } }
说明:不管是第一个数据源还是第二个数据源都需要设置实体类以及dao层;
<1> basePackages= { “com.zgx.dao” }) // 设置Repository所在位置
<2> .packages(“com.zgx.test.entity”) // 设置实体类所在位置
这两个一定要按照自己的实际情况进行修改;
private Map<String, String> getVendorProperties() { return jpaProperties.getHibernateProperties(new HibernateProperties()); }
方法在springBoot2.x版本已经不再适用,可以参照上面代码修改即可,SpringBoot1.x和2.x配置数据源主要是这里发生里变化;
五、最后
在使用上述maven依赖时会发生一个mysql时区错误
这是由于版本问题,此问题我已经在我的上一篇博客进行了总结:
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。