溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

SpringBoot怎么使用druid配置多數(shù)據(jù)源

發(fā)布時間:2023-03-11 11:41:01 來源:億速云 閱讀:136 作者:iii 欄目:開發(fā)技術

這篇“SpringBoot怎么使用druid配置多數(shù)據(jù)源”文章的知識點大部分人都不太理解,所以小編給大家總結(jié)了以下內(nèi)容,內(nèi)容詳細,步驟清晰,具有一定的借鑒價值,希望大家閱讀完這篇文章能有所收獲,下面我們一起來看看這篇“SpringBoot怎么使用druid配置多數(shù)據(jù)源”文章吧。

一、背景

使用spring boot配置多數(shù)據(jù)源,數(shù)據(jù)源分別為postgresql、mysql

二、版本介紹

  • spring boot——2.5.4

  • druid——1.2.11

  • postgresql——12

  • mysql——8.0.16

  • maven——3.0

  • idea——2019

三、項目結(jié)構

java package目錄

SpringBoot怎么使用druid配置多數(shù)據(jù)源

resource目錄存放mapper.xml文件,按照數(shù)據(jù)源創(chuàng)建package 

 SpringBoot怎么使用druid配置多數(shù)據(jù)源

四、maven依賴 

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>2.0.4</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.alibaba/druid-spring-boot-starter -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.2.11</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!-- MySql驅(qū)動 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

五、yaml配置文件

server:
  port: 8081
spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    druid:
      web-stat-filter:
        enabled: true #是否啟用StatFilter默認值true
        url-pattern: /*
        exclusions: /druid/*,*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico
        session-stat-enable: true
        session-stat-max-count: 10
      stat-view-servlet:
        enabled: true #是否啟用StatViewServlet默認值true
        url-pattern: /druid/*
        reset-enable: true
        login-username: admin
        login-password: admin
        allow:
 
      db1:
        username: postgres
        password: localhost
        url: jdbc:postgresql://localhost:5432/test
        driver-class-name: org.postgresql.Driver
        initial-size: 5  # 初始化大小
        min-idle: 5  # 最小
        max-active: 100  # 最大
        max-wait: 60000  # 配置獲取連接等待超時的時間
        validation-query: select version()
        time-between-eviction-runs-millis: 60000  # 配置間隔多久才進行一次檢測,檢測需要關閉的空閑連接,單位是毫秒
        min-evictable-idle-time-millis: 300000  # 指定一個空閑連接最少空閑多久后可被清除,單位是毫秒
        filters: config,wall,stat  # 配置監(jiān)控統(tǒng)計攔截的filters,去掉后監(jiān)控界面sql無法統(tǒng)計,'wall'用于防火墻
        # 通過connectProperties屬性來打開mergeSql功能;慢SQL記錄
        connectionProperties: druid.stat.slowSqlMillis=200;druid.stat.logSlowSql=true;config.decrypt=false
        test-while-idle: true
        test-on-borrow: true
        test-on-return: false
        # 是否緩存preparedStatement,也就是PSCache  官方建議MySQL下建議關閉   個人建議如果想用SQL防火墻 建議打開
        pool-prepared-statements: true
        max-pool-prepared-statement-per-connection-size: 20
 
      db2:
        username: root
        password: localhost
        url: jdbc:mysql://localhost:3306/springboot?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=Asia/Shanghai
        driver-class-name: com.mysql.cj.jdbc.Driver
        initial-size: 5  # 初始化大小
        min-idle: 5  # 最小
        max-active: 100  # 最大
        max-wait: 60000  # 配置獲取連接等待超時的時間
        validation-query: select 'x'
        time-between-eviction-runs-millis: 60000  # 配置間隔多久才進行一次檢測,檢測需要關閉的空閑連接,單位是毫秒
        min-evictable-idle-time-millis: 300000  # 指定一個空閑連接最少空閑多久后可被清除,單位是毫秒
        filters: config,wall,stat  # 配置監(jiān)控統(tǒng)計攔截的filters,去掉后監(jiān)控界面sql無法統(tǒng)計,'wall'用于防火墻
        # 通過connectProperties屬性來打開mergeSql功能;慢SQL記錄
        connectionProperties: druid.stat.slowSqlMillis=200;druid.stat.logSlowSql=true;config.decrypt=false
        test-while-idle: true
        test-on-borrow: true
        test-on-return: false
        # 是否緩存preparedStatement,也就是PSCache  官方建議MySQL下建議關閉   個人建議如果想用SQL防火墻 建議打開
        pool-prepared-statements: true
        max-pool-prepared-statement-per-connection-size: 20
 
mybatis:
  mapper-locations: classpath:com/demo/mapper/*.xml
  type-aliases-package: com.demo.entity
  configuration:
    log-impl:
    mapUnderscoreToCamelCase: true
 
#showSql
logging:
  level:
    java.sql: debug
    org.apache.ibatis: debug
    com.demo.mapper: debug
  config: classpath:logback-spring.xml

六、數(shù)據(jù)源配置文件

@Configuration
@MapperScan(basePackages = "com.demo.mapper.postgre.**", sqlSessionFactoryRef = "oneSqlSessionFactory")
public class DataSourceConfig1 {
    // 將這個對象放入Spring容器中
    @Bean(name = "oneDataSource")
    // 表示這個數(shù)據(jù)源是默認數(shù)據(jù)源
    @Primary
    // 讀取application.properties中的配置參數(shù)映射成為一個對象
    // prefix表示參數(shù)的前綴
    @ConfigurationProperties(prefix = "spring.datasource.druid.db1")
    public DataSource getDateSource1() {
        return DataSourceBuilder.create().type(DruidDataSource.class).build();
    }
 
    @Bean(name = "oneSqlSessionFactory")
    // 表示這個數(shù)據(jù)源是默認數(shù)據(jù)源
    @Primary
    // @Qualifier表示查找Spring容器中名字為oneDataSource的對象
    public SqlSessionFactory oneSqlSessionFactory(@Qualifier("oneDataSource") DataSource datasource)
            throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(datasource);
        bean.setMapperLocations(
                // 設置mybatis的xml所在位置
                new PathMatchingResourcePatternResolver().getResources("classpath*:com.demo.mapper.postgre/*.xml"));
        return bean.getObject();
    }
 
    @Bean("oneSqlSessionTemplate")
    // 表示這個數(shù)據(jù)源是默認數(shù)據(jù)源
    @Primary
    public SqlSessionTemplate oneSqlSessionTemplate(
            @Qualifier("oneSqlSessionFactory") SqlSessionFactory sessionFactory) {
        return new SqlSessionTemplate(sessionFactory);
    }
 
}
@Configuration
@MapperScan(basePackages = "com.demo.mapper.mysql", sqlSessionFactoryRef = "twoSqlSessionFactory")
public class DataSourceConfig2 {
    // 將這個對象放入Spring容器中
    @Bean(name = "twoDataSource")
    // 讀取application.properties中的配置參數(shù)映射成為一個對象
    // prefix表示參數(shù)的前綴
    @ConfigurationProperties(prefix = "spring.datasource.druid.db2")
    public DataSource getDateSource1() {
        return DataSourceBuilder.create().type(DruidDataSource.class).build();
    }
 
    @Bean(name = "twoSqlSessionFactory")
    // 表示這個數(shù)據(jù)源是默認數(shù)據(jù)源
    //@Primary
    // @Qualifier表示查找Spring容器中名字為oneDataSource的對象
    public SqlSessionFactory oneSqlSessionFactory(@Qualifier("twoDataSource") DataSource datasource)
            throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(datasource);
        bean.setMapperLocations(
                // 設置mybatis的xml所在位置
                new PathMatchingResourcePatternResolver().getResources("classpath*:com.demo.mapper.mysql/*.xml"));
        return bean.getObject();
    }
 
    @Bean("twoSqlSessionTemplate")
    // 表示這個數(shù)據(jù)源是默認數(shù)據(jù)源
    //@Primary
    public SqlSessionTemplate oneSqlSessionTemplate(
            @Qualifier("twoSqlSessionFactory") SqlSessionFactory sessionFactory) {
        return new SqlSessionTemplate(sessionFactory);
    }
 
}

七、啟動類配置

關鍵點:去除  exclude = {DataSourceAutoConfiguration.class} 及掃描 com.demo.mapper目錄

@MapperScan("com.demo.mapper")
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class DemoApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication .class, args);
    }
}

八、druid管理頁面

輸入地址 localhost://8081/druid,輸入 admin/admin     

以上就是關于“SpringBoot怎么使用druid配置多數(shù)據(jù)源”這篇文章的內(nèi)容,相信大家都有了一定的了解,希望小編分享的內(nèi)容對大家有幫助,若想了解更多相關的知識內(nèi)容,請關注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI