Druid是阿里开发的数据库连接池,功能强大,号称Java语言中最好的数据库连接池。本文主要介绍Srping Boot下用Druid配置多个数据源,demo环境为:Spring Boot 2.1.4.RELEASE、Druid 1.1.16。
1、引入依赖
<dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.16</version> </dependency>
2、配置数据源
在application.yml中配置druid数据源
spring: datasource: druid: db1: driverClassName: oracle.jdbc.OracleDriver url: jdbc:oracle:thin:@10.39.196.10:1521:test username: user1 password: user1 initialSize: 2 minIdle: 2 maxActive: 5 validationQuery: SELECT 1 from dual testWhileIdle: true testOnBorrow: true testOnReturn: false maxWait: 6000 filters: wall,stat,slf4j db2: driverClassName: oracle.jdbc.OracleDriver url: jdbc:oracle:thin:@10.39.196.10:1521:test username: user2 password: user2 initialSize: 2 minIdle: 2 maxActive: 5 validationQuery: SELECT 1 from dual testWhileIdle: true testOnBorrow: true testOnReturn: false maxWait: 6000
3、配置类
package com.inspur.webframe.config; import javax.sql.DataSource; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder; @Configuration public class DataSourceConfig { @Primary @Bean(name = "dataSource1") @ConfigurationProperties(prefix="spring.datasource.druid.db1") public DataSource dataSourceCmuser() { return DruidDataSourceBuilder.create().build(); } @Bean(name = "dataSource2") @ConfigurationProperties(prefix="spring.datasource.druid.db2") public DataSource dataSourceIrms() { return DruidDataSourceBuilder.create().build(); } }
4、使用
使用@Autowired或@Qualifier引用数据源
@Autowired private DataSource dataSource;//默认引用dataSource1
或
@Autowired @Qualifier("dataSource2") private DataSource dataSource;//引用dataSource2