1. 程式人生 > >Spring Boot整合Druid配置多資料來源

Spring Boot整合Druid配置多資料來源

 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;

/**
 * 
 * @author wuyy
 *
 */
@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

 

&n