Spring Boot入门实战(4)--Spring Boot 整合 Druid 配置多数据源

Druid 是阿里开发的数据库连接池,功能强大,号称Java语言中最好的数据库连接池。本文主要介绍 Srping Boot 下用Druid配置多个数据源,文中所使用到的软件版本: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.49.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.49.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.abc.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

 

5、扩展

更多扩展的使用可参考下面的文章:

Spring Boot 入门实战(5)--JdbcTempalte、Mybatis及多数据源整合(单库事务) 

Spring Boot 入门实战(6)--JdbcTempalte、Mybatis 、多数据源及 Atomicos 整合(XA 事务) 

Spring Boot 入门实战(7)--JdbcTempalte、Mybatis、动态数据源及Atomicos整合(XA 事务) 

 

posted @ 2019-11-06 20:33  且行且码  阅读(7518)  评论(0编辑  收藏  举报