• 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;
    
    @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
  • 相关阅读:
    JTAG的SWD接线方式
    Qt のEXecl
    人脸识别
    Qt实现基本QMainWindow主窗口程序
    Qt学习之路MainWindow学习过程中的知识点
    QT_FORWARD_DECLARE_CLASS
    标准的并发控制实现
    C++ DFS
    C# 互操作(一) 编写一个C++ COM组件
    Socket使用SOAP调用WCF
  • 原文地址:https://www.cnblogs.com/wuyongyin/p/11803385.html
Copyright © 2020-2023  润新知