springboot2的hikari数据库连接池默认配置

Spring-Boot-2.0.0-M1版本将默认的数据库连接池从tomcat jdbc pool改为了hikari,这里主要研究下hikari的默认配置

spring-configuration-metadata.json

spring-boot-autoconfigure-2.0.0.M7.jar!/META-INF/spring-configuration-metadata.json

    {
      "sourceType": "org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration$Hikari",
      "name": "spring.datasource.hikari",
      "sourceMethod": "dataSource(org.springframework.boot.autoconfigure.jdbc.DataSourceProperties)",
      "type": "com.zaxxer.hikari.HikariDataSource"
    },
    {
      "sourceType": "com.zaxxer.hikari.HikariDataSource",
      "name": "spring.datasource.hikari.allow-pool-suspension",
      "type": "java.lang.Boolean"
    },
    {
      "sourceType": "com.zaxxer.hikari.HikariDataSource",
      "name": "spring.datasource.hikari.auto-commit",
      "type": "java.lang.Boolean"
    },
    {
      "sourceType": "com.zaxxer.hikari.HikariDataSource",
      "name": "spring.datasource.hikari.catalog",
      "type": "java.lang.String"
    },
    {
      "sourceType": "com.zaxxer.hikari.HikariDataSource",
      "name": "spring.datasource.hikari.connection-init-sql",
      "type": "java.lang.String"
    },
    {
      "sourceType": "com.zaxxer.hikari.HikariDataSource",
      "name": "spring.datasource.hikari.connection-test-query",
      "type": "java.lang.String"
    },
    {
      "sourceType": "com.zaxxer.hikari.HikariDataSource",
      "name": "spring.datasource.hikari.connection-timeout",
      "type": "java.lang.Long"
    },
    {
      "sourceType": "com.zaxxer.hikari.HikariDataSource",
      "name": "spring.datasource.hikari.data-source-class-name",
      "type": "java.lang.String"
    },
    {
      "sourceType": "com.zaxxer.hikari.HikariDataSource",
      "name": "spring.datasource.hikari.data-source-j-n-d-i",
      "type": "java.lang.String"
    },
    {
      "sourceType": "com.zaxxer.hikari.HikariDataSource",
      "name": "spring.datasource.hikari.data-source-properties",
      "type": "java.util.Properties"
    },
    {
      "sourceType": "com.zaxxer.hikari.HikariDataSource",
      "name": "spring.datasource.hikari.driver-class-name",
      "type": "java.lang.String"
    },
    {
      "sourceType": "com.zaxxer.hikari.HikariDataSource",
      "name": "spring.datasource.hikari.health-check-properties",
      "type": "java.util.Properties"
    },
    {
      "sourceType": "com.zaxxer.hikari.HikariDataSource",
      "name": "spring.datasource.hikari.health-check-registry",
      "type": "java.lang.Object"
    },
    {
      "sourceType": "com.zaxxer.hikari.HikariDataSource",
      "name": "spring.datasource.hikari.idle-timeout",
      "type": "java.lang.Long"
    },
    {
      "sourceType": "com.zaxxer.hikari.HikariDataSource",
      "deprecated": true,
      "name": "spring.datasource.hikari.initialization-fail-fast", //initializationFailTimeout > 0
      "type": "java.lang.Boolean",
      "deprecation": {}
    },
    {
      "sourceType": "com.zaxxer.hikari.HikariDataSource",
      "name": "spring.datasource.hikari.initialization-fail-timeout",
      "type": "java.lang.Long"
    },
    {
      "sourceType": "com.zaxxer.hikari.HikariDataSource",
      "name": "spring.datasource.hikari.isolate-internal-queries",
      "type": "java.lang.Boolean"
    },
    {
      "sourceType": "com.zaxxer.hikari.HikariDataSource",
      "name": "spring.datasource.hikari.jdbc-url",
      "type": "java.lang.String"
    },
    {
      "sourceType": "com.zaxxer.hikari.HikariDataSource",
      "deprecated": true,
      "name": "spring.datasource.hikari.jdbc4-connection-test", //废弃
      "type": "java.lang.Boolean",
      "deprecation": {}
    },
    {
      "sourceType": "com.zaxxer.hikari.HikariDataSource",
      "name": "spring.datasource.hikari.leak-detection-threshold",
      "type": "java.lang.Long"
    },
    {
      "sourceType": "com.zaxxer.hikari.HikariDataSource",
      "name": "spring.datasource.hikari.login-timeout", //在HikariDataSource及PoolBase中
      "type": "java.lang.Integer"
    },
    {
      "sourceType": "com.zaxxer.hikari.HikariDataSource",
      "name": "spring.datasource.hikari.max-lifetime",
      "type": "java.lang.Long"
    },
    {
      "sourceType": "com.zaxxer.hikari.HikariDataSource",
      "name": "spring.datasource.hikari.maximum-pool-size",
      "type": "java.lang.Integer"
    },
    {
      "sourceType": "com.zaxxer.hikari.HikariDataSource",
      "name": "spring.datasource.hikari.metric-registry",
      "type": "java.lang.Object"
    },
    {
      "sourceType": "com.zaxxer.hikari.HikariDataSource",
      "name": "spring.datasource.hikari.metrics-tracker-factory",
      "type": "com.zaxxer.hikari.metrics.MetricsTrackerFactory"
    },
    {
      "sourceType": "com.zaxxer.hikari.HikariDataSource",
      "name": "spring.datasource.hikari.minimum-idle",
      "type": "java.lang.Integer"
    },
    {
      "sourceType": "com.zaxxer.hikari.HikariDataSource",
      "name": "spring.datasource.hikari.password",
      "type": "java.lang.String"
    },
    {
      "sourceType": "com.zaxxer.hikari.HikariDataSource",
      "name": "spring.datasource.hikari.pool-name",
      "type": "java.lang.String"
    },
    {
      "sourceType": "com.zaxxer.hikari.HikariDataSource",
      "name": "spring.datasource.hikari.read-only",
      "type": "java.lang.Boolean"
    },
    {
      "sourceType": "com.zaxxer.hikari.HikariDataSource",
      "name": "spring.datasource.hikari.register-mbeans",
      "type": "java.lang.Boolean"
    },
    {
      "sourceType": "com.zaxxer.hikari.HikariDataSource",
      "name": "spring.datasource.hikari.scheduled-executor",
      "type": "java.util.concurrent.ScheduledExecutorService"
    },
    {
      "sourceType": "com.zaxxer.hikari.HikariDataSource",
      "deprecated": true,
      "name": "spring.datasource.hikari.scheduled-executor-service",
      "type": "java.util.concurrent.ScheduledThreadPoolExecutor",
      "deprecation": {}
    },
    {
      "sourceType": "com.zaxxer.hikari.HikariDataSource",
      "name": "spring.datasource.hikari.schema",
      "type": "java.lang.String"
    },
    {
      "sourceType": "com.zaxxer.hikari.HikariDataSource",
      "name": "spring.datasource.hikari.transaction-isolation", //transactionIsolationName
      "type": "java.lang.String"
    },
    {
      "sourceType": "com.zaxxer.hikari.HikariDataSource",
      "name": "spring.datasource.hikari.username",
      "type": "java.lang.String"
    },
    {
      "sourceType": "com.zaxxer.hikari.HikariDataSource",
      "name": "spring.datasource.hikari.validation-timeout",
      "type": "java.lang.Long"
    },

HikariConfig

HikariCP-2.7.6-sources.jar!/com/zaxxer/hikari/HikariConfig.java

@SuppressWarnings({"SameParameterValue", "unused"})
public class HikariConfig implements HikariConfigMXBean
{
   private static final Logger LOGGER = LoggerFactory.getLogger(HikariConfig.class);

   private static final char[] ID_CHARACTERS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
   private static final long CONNECTION_TIMEOUT = SECONDS.toMillis(30);
   private static final long VALIDATION_TIMEOUT = SECONDS.toMillis(5);
   private static final long IDLE_TIMEOUT = MINUTES.toMillis(10);
   private static final long MAX_LIFETIME = MINUTES.toMillis(30);
   private static final int DEFAULT_POOL_SIZE = 10;
   //......

   /**
    * Default constructor
    */
   public HikariConfig()
   {
      dataSourceProperties = new Properties();
      healthCheckProperties = new Properties();

      minIdle = -1;
      maxPoolSize = -1;
      maxLifetime = MAX_LIFETIME;
      connectionTimeout = CONNECTION_TIMEOUT;
      validationTimeout = VALIDATION_TIMEOUT;
      idleTimeout = IDLE_TIMEOUT;
      initializationFailTimeout = 1;
      isAutoCommit = true;

      String systemProp = System.getProperty("hikaricp.configurationFile");
      if (systemProp != null) {
         loadProperties(systemProp);
      }
   }

   @Override
   public void setConnectionTimeout(long connectionTimeoutMs)
   {
      if (sealed) throw new IllegalStateException("The configuration of the pool is sealed once started.  Use HikariConfigMXBean for runtime changes.");

      if (connectionTimeoutMs == 0) {
         this.connectionTimeout = Integer.MAX_VALUE;
      }
      else if (connectionTimeoutMs < 250) {
         throw new IllegalArgumentException("connectionTimeout cannot be less than 250ms");
      }
      else {
         this.connectionTimeout = connectionTimeoutMs;
      }
   }

   @Override
   public void setIdleTimeout(long idleTimeoutMs)
   {
      if (sealed) throw new IllegalStateException("The configuration of the pool is sealed once started.  Use HikariConfigMXBean for runtime changes.");

      if (idleTimeoutMs < 0) {
         throw new IllegalArgumentException("idleTimeout cannot be negative");
      }
      this.idleTimeout = idleTimeoutMs;
   }

   @Override
   public void setMaximumPoolSize(int maxPoolSize)
   {
      if (sealed) throw new IllegalStateException("The configuration of the pool is sealed once started.  Use HikariConfigMXBean for runtime changes.");

      if (maxPoolSize < 1) {
         throw new IllegalArgumentException("maxPoolSize cannot be less than 1");
      }
      this.maxPoolSize = maxPoolSize;
   }

   @Override
   public void setMinimumIdle(int minIdle)
   {
      if (sealed) throw new IllegalStateException("The configuration of the pool is sealed once started.  Use HikariConfigMXBean for runtime changes.");

      if (minIdle < 0) {
         throw new IllegalArgumentException("minimumIdle cannot be negative");
      }
      this.minIdle = minIdle;
   }

   @Override
   public void setValidationTimeout(long validationTimeoutMs)
   {
      if (sealed) throw new IllegalStateException("The configuration of the pool is sealed once started.  Use HikariConfigMXBean for runtime changes.");

      if (validationTimeoutMs < 250) {
         throw new IllegalArgumentException("validationTimeout cannot be less than 250ms");
      }

      this.validationTimeout = validationTimeoutMs;
   }

   public void validate()
   {
      if (poolName == null) {
         poolName = generatePoolName();
      }
      else if (isRegisterMbeans && poolName.contains(":")) {
         throw new IllegalArgumentException("poolName cannot contain ':' when used with JMX");
      }

      // treat empty property as null
      catalog = getNullIfEmpty(catalog);
      connectionInitSql = getNullIfEmpty(connectionInitSql);
      connectionTestQuery = getNullIfEmpty(connectionTestQuery);
      transactionIsolationName = getNullIfEmpty(transactionIsolationName);
      dataSourceClassName = getNullIfEmpty(dataSourceClassName);
      dataSourceJndiName = getNullIfEmpty(dataSourceJndiName);
      driverClassName = getNullIfEmpty(driverClassName);
      jdbcUrl = getNullIfEmpty(jdbcUrl);

      // Check Data Source Options
      if (dataSource != null) {
         if (dataSourceClassName != null) {
            LOGGER.warn("{} - using dataSource and ignoring dataSourceClassName.", poolName);
         }
      }
      else if (dataSourceClassName != null) {
         if (driverClassName != null) {
            LOGGER.error("{} - cannot use driverClassName and dataSourceClassName together.", poolName);
            // NOTE: This exception text is referenced by a Spring Boot FailureAnalyzer, it should not be
            // changed without first notifying the Spring Boot developers.
            throw new IllegalStateException("cannot use driverClassName and dataSourceClassName together.");
         }
         else if (jdbcUrl != null) {
            LOGGER.warn("{} - using dataSourceClassName and ignoring jdbcUrl.", poolName);
         }
      }
      else if (jdbcUrl != null || dataSourceJndiName != null) {
         // ok
      }
      else if (driverClassName != null) {
         LOGGER.error("{} - jdbcUrl is required with driverClassName.", poolName);
         throw new IllegalArgumentException("jdbcUrl is required with driverClassName.");
      }
      else {
         LOGGER.error("{} - dataSource or dataSourceClassName or jdbcUrl is required.", poolName);
         throw new IllegalArgumentException("dataSource or dataSourceClassName or jdbcUrl is required.");
      }

      validateNumerics();

      if (LOGGER.isDebugEnabled() || unitTest) {
         logConfiguration();
      }
   }

   private void validateNumerics()
   {
      if (maxLifetime != 0 && maxLifetime < SECONDS.toMillis(30)) {
         LOGGER.warn("{} - maxLifetime is less than 30000ms, setting to default {}ms.", poolName, MAX_LIFETIME);
         maxLifetime = MAX_LIFETIME;
      }

      if (idleTimeout + SECONDS.toMillis(1) > maxLifetime && maxLifetime > 0) {
         LOGGER.warn("{} - idleTimeout is close to or more than maxLifetime, disabling it.", poolName);
         idleTimeout = 0;
      }

      if (idleTimeout != 0 && idleTimeout < SECONDS.toMillis(10)) {
         LOGGER.warn("{} - idleTimeout is less than 10000ms, setting to default {}ms.", poolName, IDLE_TIMEOUT);
         idleTimeout = IDLE_TIMEOUT;
      }

      if (leakDetectionThreshold > 0 && !unitTest) {
         if (leakDetectionThreshold < SECONDS.toMillis(2) || (leakDetectionThreshold > maxLifetime && maxLifetime > 0)) {
            LOGGER.warn("{} - leakDetectionThreshold is less than 2000ms or more than maxLifetime, disabling it.", poolName);
            leakDetectionThreshold = 0;
         }
      }

      if (connectionTimeout < 250) {
         LOGGER.warn("{} - connectionTimeout is less than 250ms, setting to {}ms.", poolName, CONNECTION_TIMEOUT);
         connectionTimeout = CONNECTION_TIMEOUT;
      }

      if (validationTimeout < 250) {
         LOGGER.warn("{} - validationTimeout is less than 250ms, setting to {}ms.", poolName, VALIDATION_TIMEOUT);
         validationTimeout = VALIDATION_TIMEOUT;
      }

      if (maxPoolSize < 1) {
         maxPoolSize = (minIdle <= 0) ? DEFAULT_POOL_SIZE : minIdle;
      }

      if (minIdle < 0 || minIdle > maxPoolSize) {
         minIdle = maxPoolSize;
      }
   }
}   

可以看到在set方法添加了参数校验,同时在configuration的构造器以及getConnection方法中也调用了validate方法

   public HikariDataSource(HikariConfig configuration)
   {
      configuration.validate();
      configuration.copyStateTo(this);
      this.seal();

      LOGGER.info("{} - Starting...", configuration.getPoolName());
      pool = fastPathPool = new HikariPool(this);
      LOGGER.info("{} - Start completed.", configuration.getPoolName());
   }

   /** {@inheritDoc} */
   @Override
   public Connection getConnection() throws SQLException
   {
      if (isClosed()) {
         throw new SQLException("HikariDataSource " + this + " has been closed.");
      }

      if (fastPathPool != null) {
         return fastPathPool.getConnection();
      }

      // See http://en.wikipedia.org/wiki/Double-checked_locking#Usage_in_Java
      HikariPool result = pool;
      if (result == null) {
         synchronized (this) {
            result = pool;
            if (result == null) {
               validate();
               LOGGER.info("{} - Starting...", getPoolName());
               try {
                  pool = result = new HikariPool(this);
                  this.seal();
               }
               catch (PoolInitializationException pie) {
                  if (pie.getCause() instanceof SQLException) {
                     throw (SQLException) pie.getCause();
                  }
                  else {
                     throw pie;
                  }
               }
               LOGGER.info("{} - Start completed.", getPoolName());
            }
         }
      }

      return result.getConnection();
   }

springboot的autoconfig是采用BeanUtils的反射来初始化HikariDataSource,走的是默认构造器,因此校验就依赖set方法以及后续的getConnection方法。

PoolBase.setLoginTimeout

HikariCP-2.7.6-sources.jar!/com/zaxxer/hikari/pool/PoolBase.java

   /**
    * Set the loginTimeout on the specified DataSource.
    *
    * @param dataSource the DataSource
    */
   private void setLoginTimeout(final DataSource dataSource)
   {
      if (connectionTimeout != Integer.MAX_VALUE) {
         try {
            dataSource.setLoginTimeout(Math.max(1, (int) MILLISECONDS.toSeconds(500L + connectionTimeout)));
         }
         catch (Throwable e) {
            LOGGER.info("{} - Failed to set login timeout for data source. ({})", poolName, e.getMessage());
         }
      }
   }

这个在初始化的时候设定了loginTimeout,初始值为Math.max(1, (int) MILLISECONDS.toSeconds(500L + connectionTimeout))

小结

springboot的HikariDataSource默认配置的默认值如下

name 构造器默认值 默认配置validate之后的值 validate重置
minIdle -1 10 minIdle<0或者minIdle>maxPoolSize,则被重置为maxPoolSize
maxPoolSize -1 10 如果maxPoolSize小于1,则会被重置。当minIdle<=0被重置为DEFAULT_POOL_SIZE则为10;如果minIdle>0则重置为minIdle的值
maxLifetime MINUTES.toMillis(30) = 1800000 1800000 如果不等于0且小于30秒则会被重置回30分钟
connectionTimeout SECONDS.toMillis(30) = 30000 30000 如果小于250毫秒,则被重置回30秒
validationTimeout SECONDS.toMillis(5) = 5000 5000 如果小于250毫秒,则会被重置回5秒
loginTimeout 10 30 Math.max(1, (int) MILLISECONDS.toSeconds(500L + connectionTimeout)),为connectionTimeout+500ms转为秒数取整 与 1 取最大者
idleTimeout MINUTES.toMillis(10) = 600000 600000 如果idleTimeout+1秒>maxLifetime 且 maxLifetime>0,则会被重置为0;如果idleTimeout!=0且小于10秒,则会被重置为10秒
leakDetectionThreshold 0 0 如果大于0且不是单元测试,则进一步判断:(leakDetectionThreshold < SECONDS.toMillis(2) or (leakDetectionThreshold > maxLifetime && maxLifetime > 0),会被重置为0 . 即如果要生效则必须>0,而且不能小于2秒,而且当maxLifetime > 0时不能大于maxLifetime
initializationFailTimeout 1 1 -
isAutoCommit true true -
isReadOnly false fasle -
isAllowPoolSuspension false false -
isIsolateInternalQueries false false -
isRegisterMbeans false false -
sealed false true 运行启动后这个标志为true,表示不再运行修改
poolName null HikariPool-1 -
catalog null null -
connectionInitSql null null -
connectionTestQuery null null -
dataSourceClassName null null -
schema null null -
transactionIsolationName null null -
dataSource null null -
dataSourceProperties {} {} -
threadFactory null null -
scheduledExecutor null null -
metricsTrackerFactory null null -
metricRegistry null null -
healthCheckRegistry null null -
healthCheckProperties {} {} -

doc

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 205,386评论 6 479
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,939评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,851评论 0 341
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,953评论 1 278
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,971评论 5 369
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,784评论 1 283
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,126评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,765评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,148评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,744评论 2 323
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,858评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,479评论 4 322
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,080评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,053评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,278评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,245评论 2 352
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,590评论 2 343