spring boot tomcat jdbc pool的属性绑定

转载自:http://www.voidcn.com/article/p-eujlunlh-bse.html

叙述

本文主要研究一下spring boot tomcat jdbc pool的属性绑定

错误配置

spring:
  datasource:
    type: org.apache.tomcat.jdbc.pool.DataSource
    driver-class-name: org.postgresql.Driver
    url: jdbc:postgresql://192.168.99.100:5432/postgres?connectTimeout=6000&socketTimeout=6000
    username: postgres
    password: postgres
    jmx-enabled: true
    initial-size: 1
    max-active: 5
    ## when pool sweeper is enabled, extra idle connection will be closed
    max-idle: 5
    ## when idle connection > min-idle, poolSweeper will start to close
    min-idle: 1

使用如上配置,最后发现initial-size,max-active,max-idle,min-idle等配置均无效,生成的tomcat jdbc datasource还是使用的默认的配置

正确配置

spring:
  datasource:
    type: org.apache.tomcat.jdbc.pool.DataSource
    driver-class-name: org.postgresql.Driver
    url: jdbc:postgresql://192.168.99.100:5432/postgres?connectTimeout=6000&socketTimeout=6000
    username: postgres
    password: postgres
    jmx-enabled: true
    tomcat:  ## 单个数据库连接池,而且得写上tomcat的属性配置才可以生效
      initial-size: 1
      max-active: 5
      ## when pool sweeper is enabled, extra idle connection will be closed
      max-idle: 5
      ## when idle connection > min-idle, poolSweeper will start to close
      min-idle: 1

注意,这里把具体tomcat数据库连接池的配置属性放到了spring.datasource.tomcat属性下面,这样才可以生效。

多数据源的配置

上面的配置对于单数据源来说是没有问题的,对于多数据源,则配置如下

@Configuration
public class MasterDatasourceConfig {

    @Bean("masterDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.master")
    public DataSource masterDataSource() {
        return DataSourceBuilder.create().build();
    }
}

注意,这里要添加ConfigurationProperties注入tomcat jdbc pool的额外设置

spring:
  datasource:
    master:
      type: org.apache.tomcat.jdbc.pool.DataSource
      driver-class-name: org.postgresql.Driver
      url: jdbc:postgresql://192.168.99.100:5432/postgres?connectTimeout=6000&socketTimeout=6000
      username: postgres
      password: postgres
      jmx-enabled: true
#    tomcat: ## 多数据源的话,这里要去掉tomcat,通通放在数据源前缀下面
      initial-size: 1
      max-active: 5
      ## when pool sweeper is enabled, extra idle connection will be closed
      max-idle: 5
      ## when idle connection > min-idle, poolSweeper will start to close
      min-idle: 1

原先tomcat的配置都要放在数据源前缀的底下,放在spring.datasource.tomcat或者spring.datasource.master.tomcat底下均无法生效。

小结

spirngboot的自动配置是挺方便的,但是在实际应用的场景下还需要了解底层机制才可以,否则容易出来配置假象,以为配置对了,实际没生效。

发布了22 篇原创文章 · 获赞 30 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/lizhengyu891231/article/details/103275662