【追光者系列】HikariCP 源码分析之故障检测那些思考 fail fast & allowPoolSuspension...

HikariPool-1 - Interrupted during connection acquisition HikariPool-1 - Interrupted during connection acquisition问题描述临时解决办法根本原因 最近在压测springboot服务的是时候,遇到HikariPool-1 - Interrupted during connection acquisition,先记录一下临时解决办法,后面有时间在review这个问题。 问题描述 问题日志: Caused by: org.apache.ibatis.exceptions.PersistenceException: 阅读详情

点击上方“芋道源码”,选择“置顶公众号”

技术文章第一时间送达!

源码精品专栏

 

摘要: 原创出处 https://mp.weixin.qq.com/s/awLR5hZC_Bbv2znJT218bQ 「渣渣王子」欢迎转载,保留摘要,谢谢!

  • 模拟数据库挂掉

  • allowPoolSuspension

  • 参考资料


由于时间原因,本文主要内容参考了 https://segmentfault.com/a/1190000013136251 ,并结合一些思考做了增注

模拟数据库挂掉

首先解释一下connectionTimeout的意思,这并不是获取连接的超时时间,而是从连接池返回连接的超时时间。
SQL执行的超时时间,JDBC 可以直接使用 Statement.setQueryTimeout,Spring 可以使用 @Transactional(timeout=10)。

connectionTimeout
This property controls the maximum number of milliseconds that a client (that's you) will wait for a connection from the pool. If this time is exceeded without a connection becoming available, a SQLException will be thrown. Lowest acceptable connection timeout is 250 ms. Default: 30000 (30 seconds)

如果是没有空闲连接且连接池满不能新建连接的情况下,hikari则是阻塞connectionTimeout的时间,没有得到连接抛出SQLTransientConnectionException。

如果是有空闲连接的情况,hikari是在connectionTimeout时间内不断循环获取下一个空闲连接进行校验,校验失败继续获取下一个空闲连接,直到超时抛出SQLTransientConnectionException。(hikari在获取一个连接的时候,会在connectionTimeout时间内循环把空闲连接挨个validate一次,最后timeout抛出异常;之后的获取连接操作,则一直阻塞connectionTimeout时间再抛出异常)

如果微服务使用了连接的健康监测,如果你catch了此异常,就会不断的打出健康监测的错误。

hikari如果connectionTimeout设置太大的话,在数据库挂的时候,很容易阻塞业务线程

根据以上结论我们撸一遍源码,首先看一下getConnection的源码,大致流程是如果borrow的poolEntry为空,就会跳出循环,抛异常,包括超时时间也会打出来如下:

java.sql.SQLTransientConnectionException: communications-link-failure-db - Connection is not available, request timed out after 447794ms.
    at com.zaxxer.hikari.pool.HikariPool.createTimeoutException(HikariPool.java:666)
    at com.zaxxer.hikari.pool.HikariPool.getConnection(HikariPool.java:182)
    at com.zaxxer.hikari.pool.HikariPool.getConnection(HikariPool.java:147)
/**
    * Get a connection from the pool, or timeout after the specified number of milliseconds.
    *
    * @param hardTimeout the maximum time to wait for a connection from the pool
    * @return a java.sql.Connection instance
    * @throws SQLException thrown if a timeout occurs trying to obtain a connection
    */
   public Connection getConnection(final long hardTimeout) throws SQLException
   {
      suspendResumeLock.acquire();
      final long startTime = currentTime();
      try {
         long timeout = hardTimeout;
         do {
            PoolEntry poolEntry = connectionBag.borrow(timeout, MILLISECONDS);
            if (poolEntry == null) {
               break; // We timed out... break and throw exception
            }
            final long now = currentTime();
            if (poolEntry.isMarkedEvicted() || (elapsedMillis(poolEntry.lastAccessed, now) > ALIVE_BYPASS_WINDOW_MS && !isConnectionAlive(poolEntry.connection))) {
               closeConnection(poolEntry, poolEntry.isMarkedEvicted() ? EVICTED_CONNECTION_MESSAGE : DEAD_CONNECTION_MESSAGE);
               timeout = hardTimeout - elapsedMillis(startTime);
            }
            else {
               metricsTracker.recordBorrowStats(poolEntry, startTime);
               return poolEntry.createProxyConnection(leakTaskFactory.schedule(poolEntry), now);
            }
         } while (timeout > 0L);
         metricsTracker.recordBorrowTimeoutStats(startTime);
         throw createTimeoutException(startTime);
      }
      catch (InterruptedException e) {
         Thread.currentThread().interrupt();
         throw new SQLException(poolName + " - Interrupted during connection acquisition", e);
      }
      finally {
         suspendResumeLock.release();
      }
   }

我们聚焦一下borrow源码,该方法的意思和其注释所说的一样,The method will borrow a BagEntry from the bag, blocking for the specified timeout if none are available.
那么final T bagEntry = handoffQueue.poll(timeout, NANOSECONDS); 这段代码就是在数据库挂掉的情况下,会产生一段耗时的地方

   /**
    * The method will borrow a BagEntry from the bag, blocking for the
    * specified timeout if none are available.
    *
    * @param timeout how long to wait before giving up, in units of unit
    * @param timeUnit a <code>TimeUnit</code> determining how to interpret the timeout parameter
    * @return a borrowed instance from the bag or null if a timeout occurs
    * @throws InterruptedException if interrupted while waiting
    */
   public T borrow(long timeout, final TimeUnit timeUnit) throws InterruptedException
   {
      // Try the thread-local list first
      final List<Object> list = threadList.get();
      for (int i = list.size() - 1; i >= 0; i--) {
         final Object entry = list.remove(i);
         @SuppressWarnings("unchecked")
         final T bagEntry = weakThreadLocals ? ((WeakReference<T>) entry).get() : (T) entry;
         if (bagEntry != null && bagEntry.compareAndSet(STATE_NOT_IN_USE, STATE_IN_USE)) {
            return bagEntry;
         }
      }
      // Otherwise, scan the shared list ... then poll the handoff queue
      final int waiting = waiters.incrementAndGet();
      try {
         for (T bagEntry : sharedList) {
            if (bagEntry.compareAndSet(STATE_NOT_IN_USE, STATE_IN_USE)) {
               // If we may have stolen another waiter's connection, request another bag add.
               if (waiting > 1) {
                  listener.addBagItem(waiting - 1);
               }
               return bagEntry;
            }
         }
         listener.addBagItem(waiting);
         timeout = timeUnit.toNanos(timeout);
         do {
            final long start = currentTime();
            final T bagEntry = handoffQueue.poll(timeout, NANOSECONDS);
            if (bagEntry == null || bagEntry.compareAndSet(STATE_NOT_IN_USE, STATE_IN_USE)) {
               return bagEntry;
            }
            timeout -= elapsedNanos(start);
         } while (timeout > 10_000);
         return null;
      }
      finally {
         waiters.decrementAndGet();
      }
   }

这里使用了JUC的SynchronousQueue

/**
     * Retrieves and removes the head of this queue, waiting
     * if necessary up to the specified wait time, for another thread
     * to insert it.
     *
     * @return the head of this queue, or {@code null} if the
     *         specified waiting time elapses before an element is present
     * @throws InterruptedException {@inheritDoc}
     */
    public E poll(long timeout, TimeUnit unit) throws InterruptedException {
        E e = transferer.transfer(null, true, unit.toNanos(timeout));
        if (e != null || !Thread.interrupted())
            return e;
        throw new InterruptedException();
    }

此时拿到空的poolEntry在getConnection中跳出循环,抛异常

HikariPool还有一个内部类叫PoolEntryCreator

 /**
    * Creating and adding poolEntries (connections) to the pool.
    */
   private final class PoolEntryCreator implements Callable<Boolean>
   {
      private final String loggingPrefix;
      PoolEntryCreator(String loggingPrefix)
      {
         this.loggingPrefix = loggingPrefix;
      }
      @Override
      public Boolean call() throws Exception
      {
         long sleepBackoff = 250L;
         while (poolState == POOL_NORMAL && shouldCreateAnotherConnection()) {
            final PoolEntry poolEntry = createPoolEntry();
            if (poolEntry != null) {
               connectionBag.add(poolEntry);
               LOGGER.debug("{} - Added connection {}", poolName, poolEntry.connection);
               if (loggingPrefix != null) {
                  logPoolState(loggingPrefix);
               }
               return Boolean.TRUE;
            }
            // failed to get connection from db, sleep and retry
            quietlySleep(sleepBackoff);
            sleepBackoff = Math.min(SECONDS.toMillis(10), Math.min(connectionTimeout, (long) (sleepBackoff * 1.5)));
         }
         // Pool is suspended or shutdown or at max size
         return Boolean.FALSE;
      }
      /**
       * We only create connections if we need another idle connection or have threads still waiting
       * for a new connection.  Otherwise we bail out of the request to create.
       *
       * @return true if we should create a connection, false if the need has disappeared
       */
      private boolean shouldCreateAnotherConnection() {
         return getTotalConnections() < config.getMaximumPoolSize() &&
            (connectionBag.getWaitingThreadCount() > 0 || getIdleConnections() < config.getMinimumIdle());
      }
   }

shouldCreateAnotherConnection方法决定了是否需要添加新的连接

HikariPool初始化的时候会初始化两个PoolEntryCreator,分别是POOL_ENTRY_CREATOR和POST_FILL_POOL_ENTRY_CREATOR,是两个异步线程

 private final PoolEntryCreator POOL_ENTRY_CREATOR = new PoolEntryCreator(null /*logging prefix*/);
   private final PoolEntryCreator POST_FILL_POOL_ENTRY_CREATOR = new PoolEntryCreator("After adding ");

POOL_ENTRY_CREATOR主要是会被private final ThreadPoolExecutor addConnectionExecutor;调用到,一处是fillPool,从当前的空闲连接(在执行时被感知到的)填充到minimumIdle(HikariCP尝试在池中维护的最小空闲连接数,如果空闲连接低于此值并且池中的总连接数少于maximumPoolSize,HikariCP将尽最大努力快速高效地添加其他连接)。
补充新连接也会遭遇Connection refused相关的异常。

  /**
    * Fill pool up from current idle connections (as they are perceived at the point of execution) to minimumIdle connections.
    */
   private synchronized void fillPool()
   {
      final int connectionsToAdd = Math.min(config.getMaximumPoolSize() - getTotalConnections(), config.getMinimumIdle() - getIdleConnections())
                                   - addConnectionQueue.size();
      for (int i = 0; i < connectionsToAdd; i++) {
         addConnectionExecutor.submit((i < connectionsToAdd - 1) ? POOL_ENTRY_CREATOR : POST_FILL_POOL_ENTRY_CREATOR);
      }
   }

还有一处是addBagItem

/** {@inheritDoc} */
   @Override
   public void addBagItem(final int waiting)
   {
      final boolean shouldAdd = waiting - addConnectionQueue.size() >= 0; // Yes, >= is intentional.
      if (shouldAdd) {
         addConnectionExecutor.submit(POOL_ENTRY_CREATOR);
      }
   }

最后再补充两个属性idleTimeout和minimumIdle

idleTimeout
This property controls the maximum amount of time that a connection is allowed to sit idle in the pool. This setting only applies when minimumIdle is defined to be less than maximumPoolSize. Idle connections will not be retired once the pool reaches minimumIdle connections. Whether a connection is retired as idle or not is subject to a maximum variation of +30 seconds, and average variation of +15 seconds. A connection will never be retired as idle before this timeout. A value of 0 means that idle connections are never removed from the pool. The minimum allowed value is 10000ms (10 seconds). Default: 600000 (10 minutes)

默认是600000毫秒,即10分钟。如果idleTimeout+1秒>maxLifetime 且 maxLifetime>0,则会被重置为0;如果idleTimeout!=0且小于10秒,则会被重置为10秒。如果idleTimeout=0则表示空闲的连接在连接池中永远不被移除。

只有当minimumIdle小于maximumPoolSize时,这个参数才生效,当空闲连接数超过minimumIdle,而且空闲时间超过idleTimeout,则会被移除。

minimumIdle
This property controls the minimum number of idle connections that HikariCP tries to maintain in the pool. If the idle connections dip below this value and total connections in the pool are less than maximumPoolSize, HikariCP will make a best effort to add additional connections quickly and efficiently. However, for maximum performance and responsiveness to spike demands, we recommend not setting this value and instead allowing HikariCP to act as a fixed size connection pool. Default: same as maximumPoolSize

控制连接池空闲连接的最小数量,当连接池空闲连接少于minimumIdle,而且总共连接数不大于maximumPoolSize时,HikariCP会尽力补充新的连接。为了性能考虑,不建议设置此值,而是让HikariCP把连接池当做固定大小的处理,默认minimumIdle与maximumPoolSize一样。
当 minIdle<0 或者 minIdle>maxPoolSize, 则被重置为maxPoolSize,该值默认为10。

Hikari会启动一个HouseKeeper定时任务,在HikariPool构造器里头初始化,默认的是初始化后100毫秒执行,之后每执行完一次之后隔HOUSEKEEPING_PERIOD_MS(30秒)时间执行。
这个定时任务的作用就是根据idleTimeout的值,移除掉空闲超时的连接。
首先检测时钟是否倒退,如果倒退了则立即对过期的连接进行标记evict;之后当idleTimeout>0且配置的minimumIdle<maximumPoolSize时才开始处理超时的空闲连接。
取出状态是STATE_NOT_IN_USE的连接数,如果大于minimumIdle,则遍历STATE_NOT_IN_USE的连接的连接,将空闲超时达到idleTimeout的连接从connectionBag移除掉,若移除成功则关闭该连接,然后toRemove--。
在空闲连接移除之后,再调用fillPool,尝试补充空间连接数到minimumIdle值

hikari的连接泄露是每次getConnection的时候单独触发一个延时任务来处理,而空闲连接的清除则是使用HouseKeeper定时任务来处理,其运行间隔由com.zaxxer.hikari.housekeeping.periodMs环境变量控制,默认为30秒。

allowPoolSuspension

关于这个参数,用来标记释放允许暂停连接池,一旦被暂停,所有的getConnection方法都会被阻塞。

作者是这么说的:
https://github.com/brettwooldridge/HikariCP/issues/1060

All of the suspend use cases I have heard have centered around a pattern of:

  • Suspend the pool.

  • Alter the pool configuration, or alter DNS configuration (to point to a new master).

  • Soft-evict existing connections.

  • Resume the pool.

我做过试验,Suspend期间getConnection确实不会超时,SQL执行都会被保留下来,软驱除现有连接之后,一直保持到池恢复Resume时,这些SQL依然会继续执行,也就是说用户并不会丢数据。
但是在实际生产中,不影响业务很难,即使继续执行,业务也可能超时了。
故障注入是中间件开发应该要做的,这个点的功能在实现chaosmonkey以模拟数据库连接故障,但是监控过程中我发现hikaricp_pending_threads指标并没有提升、MBean的threadAwaitingConnections也没有改变,所以包括故障演练以后也可以不用搞得那么复杂,收拢在中间件内部做可能更好,前提是对于这个参数,中间件还需要自研以增加模拟抛异常或是一些监控指标进行加强。
另外,长期阻塞该参数存在让微服务卡死的风险。

详细推荐看一下 【追光者系列】HikariCP源码分析之allowPoolSuspension

参考资料

https://segmentfault.com/u/codecraft/articles?page=4

666. 彩蛋


摘要: 原创出处 https://mp.weixin.qq.com/s/awLR5hZC_Bbv2znJT218bQ 「渣渣王子」欢迎转载,保留摘要,谢谢!

  • 模拟数据库挂掉

  • allowPoolSuspension

  • 参考资料


由于时间原因,本文主要内容参考了 https://segmentfault.com/a/1190000013136251 ,并结合一些思考做了增注

模拟数据库挂掉

首先解释一下connectionTimeout的意思,这并不是获取连接的超时时间,而是从连接池返回连接的超时时间。
SQL执行的超时时间,JDBC 可以直接使用 Statement.setQueryTimeout,Spring 可以使用 @Transactional(timeout=10)。

connectionTimeout
This property controls the maximum number of milliseconds that a client (that's you) will wait for a connection from the pool. If this time is exceeded without a connection becoming available, a SQLException will be thrown. Lowest acceptable connection timeout is 250 ms. Default: 30000 (30 seconds)

如果是没有空闲连接且连接池满不能新建连接的情况下,hikari则是阻塞connectionTimeout的时间,没有得到连接抛出SQLTransientConnectionException。

如果是有空闲连接的情况,hikari是在connectionTimeout时间内不断循环获取下一个空闲连接进行校验,校验失败继续获取下一个空闲连接,直到超时抛出SQLTransientConnectionException。(hikari在获取一个连接的时候,会在connectionTimeout时间内循环把空闲连接挨个validate一次,最后timeout抛出异常;之后的获取连接操作,则一直阻塞connectionTimeout时间再抛出异常)

如果微服务使用了连接的健康监测,如果你catch了此异常,就会不断的打出健康监测的错误。

hikari如果connectionTimeout设置太大的话,在数据库挂的时候,很容易阻塞业务线程

根据以上结论我们撸一遍源码,首先看一下getConnection的源码,大致流程是如果borrow的poolEntry为空,就会跳出循环,抛异常,包括超时时间也会打出来如下:

java.sql.SQLTransientConnectionException: communications-link-failure-db - Connection is not available, request timed out after 447794ms.
    at com.zaxxer.hikari.pool.HikariPool.createTimeoutException(HikariPool.java:666)
    at com.zaxxer.hikari.pool.HikariPool.getConnection(HikariPool.java:182)
    at com.zaxxer.hikari.pool.HikariPool.getConnection(HikariPool.java:147)
/**
    * Get a connection from the pool, or timeout after the specified number of milliseconds.
    *
    * @param hardTimeout the maximum time to wait for a connection from the pool
    * @return a java.sql.Connection instance
    * @throws SQLException thrown if a timeout occurs trying to obtain a connection
    */
   public Connection getConnection(final long hardTimeout) throws SQLException
   {
      suspendResumeLock.acquire();
      final long startTime = currentTime();
      try {
         long timeout = hardTimeout;
         do {
            PoolEntry poolEntry = connectionBag.borrow(timeout, MILLISECONDS);
            if (poolEntry == null) {
               break; // We timed out... break and throw exception
            }
            final long now = currentTime();
            if (poolEntry.isMarkedEvicted() || (elapsedMillis(poolEntry.lastAccessed, now) > ALIVE_BYPASS_WINDOW_MS && !isConnectionAlive(poolEntry.connection))) {
               closeConnection(poolEntry, poolEntry.isMarkedEvicted() ? EVICTED_CONNECTION_MESSAGE : DEAD_CONNECTION_MESSAGE);
               timeout = hardTimeout - elapsedMillis(startTime);
            }
            else {
               metricsTracker.recordBorrowStats(poolEntry, startTime);
               return poolEntry.createProxyConnection(leakTaskFactory.schedule(poolEntry), now);
            }
         } while (timeout > 0L);
         metricsTracker.recordBorrowTimeoutStats(startTime);
         throw createTimeoutException(startTime);
      }
      catch (InterruptedException e) {
         Thread.currentThread().interrupt();
         throw new SQLException(poolName + " - Interrupted during connection acquisition", e);
      }
      finally {
         suspendResumeLock.release();
      }
   }

我们聚焦一下borrow源码,该方法的意思和其注释所说的一样,The method will borrow a BagEntry from the bag, blocking for the specified timeout if none are available.
那么final T bagEntry = handoffQueue.poll(timeout, NANOSECONDS); 这段代码就是在数据库挂掉的情况下,会产生一段耗时的地方

   /**
    * The method will borrow a BagEntry from the bag, blocking for the
    * specified timeout if none are available.
    *
    * @param timeout how long to wait before giving up, in units of unit
    * @param timeUnit a <code>TimeUnit</code> determining how to interpret the timeout parameter
    * @return a borrowed instance from the bag or null if a timeout occurs
    * @throws InterruptedException if interrupted while waiting
    */
   public T borrow(long timeout, final TimeUnit timeUnit) throws InterruptedException
   {
      // Try the thread-local list first
      final List<Object> list = threadList.get();
      for (int i = list.size() - 1; i >= 0; i--) {
         final Object entry = list.remove(i);
         @SuppressWarnings("unchecked")
         final T bagEntry = weakThreadLocals ? ((WeakReference<T>) entry).get() : (T) entry;
         if (bagEntry != null && bagEntry.compareAndSet(STATE_NOT_IN_USE, STATE_IN_USE)) {
            return bagEntry;
         }
      }
      // Otherwise, scan the shared list ... then poll the handoff queue
      final int waiting = waiters.incrementAndGet();
      try {
         for (T bagEntry : sharedList) {
            if (bagEntry.compareAndSet(STATE_NOT_IN_USE, STATE_IN_USE)) {
               // If we may have stolen another waiter's connection, request another bag add.
               if (waiting > 1) {
                  listener.addBagItem(waiting - 1);
               }
               return bagEntry;
            }
         }
         listener.addBagItem(waiting);
         timeout = timeUnit.toNanos(timeout);
         do {
            final long start = currentTime();
            final T bagEntry = handoffQueue.poll(timeout, NANOSECONDS);
            if (bagEntry == null || bagEntry.compareAndSet(STATE_NOT_IN_USE, STATE_IN_USE)) {
               return bagEntry;
            }
            timeout -= elapsedNanos(start);
         } while (timeout > 10_000);
         return null;
      }
      finally {
         waiters.decrementAndGet();
      }
   }

这里使用了JUC的SynchronousQueue

/**
     * Retrieves and removes the head of this queue, waiting
     * if necessary up to the specified wait time, for another thread
     * to insert it.
     *
     * @return the head of this queue, or {@code null} if the
     *         specified waiting time elapses before an element is present
     * @throws InterruptedException {@inheritDoc}
     */
    public E poll(long timeout, TimeUnit unit) throws InterruptedException {
        E e = transferer.transfer(null, true, unit.toNanos(timeout));
        if (e != null || !Thread.interrupted())
            return e;
        throw new InterruptedException();
    }

此时拿到空的poolEntry在getConnection中跳出循环,抛异常

HikariPool还有一个内部类叫PoolEntryCreator

 /**
    * Creating and adding poolEntries (connections) to the pool.
    */
   private final class PoolEntryCreator implements Callable<Boolean>
   {
      private final String loggingPrefix;
      PoolEntryCreator(String loggingPrefix)
      {
         this.loggingPrefix = loggingPrefix;
      }
      @Override
      public Boolean call() throws Exception
      {
         long sleepBackoff = 250L;
         while (poolState == POOL_NORMAL && shouldCreateAnotherConnection()) {
            final PoolEntry poolEntry = createPoolEntry();
            if (poolEntry != null) {
               connectionBag.add(poolEntry);
               LOGGER.debug("{} - Added connection {}", poolName, poolEntry.connection);
               if (loggingPrefix != null) {
                  logPoolState(loggingPrefix);
               }
               return Boolean.TRUE;
            }
            // failed to get connection from db, sleep and retry
            quietlySleep(sleepBackoff);
            sleepBackoff = Math.min(SECONDS.toMillis(10), Math.min(connectionTimeout, (long) (sleepBackoff * 1.5)));
         }
         // Pool is suspended or shutdown or at max size
         return Boolean.FALSE;
      }
      /**
       * We only create connections if we need another idle connection or have threads still waiting
       * for a new connection.  Otherwise we bail out of the request to create.
       *
       * @return true if we should create a connection, false if the need has disappeared
       */
      private boolean shouldCreateAnotherConnection() {
         return getTotalConnections() < config.getMaximumPoolSize() &&
            (connectionBag.getWaitingThreadCount() > 0 || getIdleConnections() < config.getMinimumIdle());
      }
   }

shouldCreateAnotherConnection方法决定了是否需要添加新的连接

HikariPool初始化的时候会初始化两个PoolEntryCreator,分别是POOL_ENTRY_CREATOR和POST_FILL_POOL_ENTRY_CREATOR,是两个异步线程

 private final PoolEntryCreator POOL_ENTRY_CREATOR = new PoolEntryCreator(null /*logging prefix*/);
   private final PoolEntryCreator POST_FILL_POOL_ENTRY_CREATOR = new PoolEntryCreator("After adding ");

POOL_ENTRY_CREATOR主要是会被private final ThreadPoolExecutor addConnectionExecutor;调用到,一处是fillPool,从当前的空闲连接(在执行时被感知到的)填充到minimumIdle(HikariCP尝试在池中维护的最小空闲连接数,如果空闲连接低于此值并且池中的总连接数少于maximumPoolSize,HikariCP将尽最大努力快速高效地添加其他连接)。
补充新连接也会遭遇Connection refused相关的异常。

  /**
    * Fill pool up from current idle connections (as they are perceived at the point of execution) to minimumIdle connections.
    */
   private synchronized void fillPool()
   {
      final int connectionsToAdd = Math.min(config.getMaximumPoolSize() - getTotalConnections(), config.getMinimumIdle() - getIdleConnections())
                                   - addConnectionQueue.size();
      for (int i = 0; i < connectionsToAdd; i++) {
         addConnectionExecutor.submit((i < connectionsToAdd - 1) ? POOL_ENTRY_CREATOR : POST_FILL_POOL_ENTRY_CREATOR);
      }
   }

还有一处是addBagItem

/** {@inheritDoc} */
   @Override
   public void addBagItem(final int waiting)
   {
      final boolean shouldAdd = waiting - addConnectionQueue.size() >= 0; // Yes, >= is intentional.
      if (shouldAdd) {
         addConnectionExecutor.submit(POOL_ENTRY_CREATOR);
      }
   }

最后再补充两个属性idleTimeout和minimumIdle

idleTimeout
This property controls the maximum amount of time that a connection is allowed to sit idle in the pool. This setting only applies when minimumIdle is defined to be less than maximumPoolSize. Idle connections will not be retired once the pool reaches minimumIdle connections. Whether a connection is retired as idle or not is subject to a maximum variation of +30 seconds, and average variation of +15 seconds. A connection will never be retired as idle before this timeout. A value of 0 means that idle connections are never removed from the pool. The minimum allowed value is 10000ms (10 seconds). Default: 600000 (10 minutes)

默认是600000毫秒,即10分钟。如果idleTimeout+1秒>maxLifetime 且 maxLifetime>0,则会被重置为0;如果idleTimeout!=0且小于10秒,则会被重置为10秒。如果idleTimeout=0则表示空闲的连接在连接池中永远不被移除。

只有当minimumIdle小于maximumPoolSize时,这个参数才生效,当空闲连接数超过minimumIdle,而且空闲时间超过idleTimeout,则会被移除。

minimumIdle
This property controls the minimum number of idle connections that HikariCP tries to maintain in the pool. If the idle connections dip below this value and total connections in the pool are less than maximumPoolSize, HikariCP will make a best effort to add additional connections quickly and efficiently. However, for maximum performance and responsiveness to spike demands, we recommend not setting this value and instead allowing HikariCP to act as a fixed size connection pool. Default: same as maximumPoolSize

控制连接池空闲连接的最小数量,当连接池空闲连接少于minimumIdle,而且总共连接数不大于maximumPoolSize时,HikariCP会尽力补充新的连接。为了性能考虑,不建议设置此值,而是让HikariCP把连接池当做固定大小的处理,默认minimumIdle与maximumPoolSize一样。
当 minIdle<0 或者 minIdle>maxPoolSize, 则被重置为maxPoolSize,该值默认为10。

Hikari会启动一个HouseKeeper定时任务,在HikariPool构造器里头初始化,默认的是初始化后100毫秒执行,之后每执行完一次之后隔HOUSEKEEPING_PERIOD_MS(30秒)时间执行。
这个定时任务的作用就是根据idleTimeout的值,移除掉空闲超时的连接。
首先检测时钟是否倒退,如果倒退了则立即对过期的连接进行标记evict;之后当idleTimeout>0且配置的minimumIdle<maximumPoolSize时才开始处理超时的空闲连接。
取出状态是STATE_NOT_IN_USE的连接数,如果大于minimumIdle,则遍历STATE_NOT_IN_USE的连接的连接,将空闲超时达到idleTimeout的连接从connectionBag移除掉,若移除成功则关闭该连接,然后toRemove--。
在空闲连接移除之后,再调用fillPool,尝试补充空间连接数到minimumIdle值

hikari的连接泄露是每次getConnection的时候单独触发一个延时任务来处理,而空闲连接的清除则是使用HouseKeeper定时任务来处理,其运行间隔由com.zaxxer.hikari.housekeeping.periodMs环境变量控制,默认为30秒。

allowPoolSuspension

关于这个参数,用来标记释放允许暂停连接池,一旦被暂停,所有的getConnection方法都会被阻塞。

作者是这么说的:
https://github.com/brettwooldridge/HikariCP/issues/1060

All of the suspend use cases I have heard have centered around a pattern of:

  • Suspend the pool.

  • Alter the pool configuration, or alter DNS configuration (to point to a new master).

  • Soft-evict existing connections.

  • Resume the pool.

我做过试验,Suspend期间getConnection确实不会超时,SQL执行都会被保留下来,软驱除现有连接之后,一直保持到池恢复Resume时,这些SQL依然会继续执行,也就是说用户并不会丢数据。
但是在实际生产中,不影响业务很难,即使继续执行,业务也可能超时了。
故障注入是中间件开发应该要做的,这个点的功能在实现chaosmonkey以模拟数据库连接故障,但是监控过程中我发现hikaricp_pending_threads指标并没有提升、MBean的threadAwaitingConnections也没有改变,所以包括故障演练以后也可以不用搞得那么复杂,收拢在中间件内部做可能更好,前提是对于这个参数,中间件还需要自研以增加模拟抛异常或是一些监控指标进行加强。
另外,长期阻塞该参数存在让微服务卡死的风险。

详细推荐看一下 【追光者系列】HikariCP源码分析之allowPoolSuspension

参考资料

https://segmentfault.com/u/codecraft/articles?page=4

666. 彩蛋



如果你对 Dubbo 感兴趣,欢迎加入我的知识星球一起交流。


知识星球

目前在知识星球(https://t.zsxq.com/2VbiaEu)更新了如下 Dubbo 源码解析如下:

01. 调试环境搭建
02. 项目结构一览
03. 配置 Configuration
04. 核心流程一览

05. 拓展机制 SPI

06. 线程池

07. 服务暴露 Export

08. 服务引用 Refer

09. 注册中心 Registry

10. 动态编译 Compile

11. 动态代理 Proxy

12. 服务调用 Invoke

13. 调用特性 

14. 过滤器 Filter

15. NIO 服务器

16. P2P 服务器

17. HTTP 服务器

18. 序列化 Serialization

19. 集群容错 Cluster

20. 优雅停机

21. 日志适配

22. 状态检查

23. 监控中心 Monitor

24. 管理中心 Admin

25. 运维命令 QOS

26. 链路追踪 Tracing

...
一共 60 篇++

HikariPool-1 - Connection is not available, request timed out after 6000ms Connection is not available, request timed out after 6000ms问题排查论证通过demo重现问题总结 问题 今天项目上频繁出现了大量的这样的报错 Caused by: java.sql.SQLTransientConnectionException: HikariPool-1 - Connection is not available, request timed out after 6000ms. at com.zaxxer.hikari.pool. 阅读详情

相关推荐

正确解决java.sql.SQLTimeoutException异常的有效解决方法

正确解决java.sql.SQLTimeoutException异常的有效解决方法

wbajsjhhhhh的博客 2632

SpringBoot使用HikriCP数据源连接池整合Mybatis,MappperXML版

Springboot2.0之后,推荐使用HikriCP作为数据源连接池,笔者也查过多方的资料,虽然没有测过HikriCP的效率和性能,但是多方验证它很强,Spring也默认,必定有它的道理 那么今天我们就使用HikriCP来整合SpringBoot和Mybatis,Mybatis是XML版的,笔者之后会发注解版的和混合版的。 开始吧,首先的数据源要有,笔者采用的是MySQL8.0.16版,查询...

a907691592的博客 1089

UE5 VlcMedia 插件编译与流媒体播放实战

本文详细介绍了在虚幻引擎5中编译并集成VlcMedia插件以解决流媒体播放难题的实战指南。针对UE5不再默认支持Win32 API导致的编译错误,文章提供了核心的构建配置文件修改步骤,并指导如何启用插件、创建VLC媒体播放器,最终成功播放如.m3u8等格式的网络直播流或点播视频。

weixin_29013129的博客 339

记一次数据池连接失败异常, java.sql.SQLTransientConnectionException: Connection is not available

Hikari、SQLTransientConnectionException、假死,sql执行超时时间

xybz1993的博客 7428

Python结合海康威视工业相机SDK实现高效图像采集与处理

本文详细介绍了如何使用Python结合海康威视工业相机SDK实现高效的图像采集与处理。内容涵盖从环境搭建、SDK核心模块理解,到完整的图像采集流程拆解,包括设备枚举、参数设置、主动取流以及关键的像素格式转换。同时,文章深入探讨了触发模式、参数控制等高级应用,并提供了性能优化建议和可复用的相机操作类封装,帮助开发者快速构建稳定的机器视觉应用。

weixin_29043895的博客 350

CKS-CN考试之路----11

显然是alpine-b的镜像有libcrypto3-3.1.4-r5。新版本发布老版本会被回收,此时pod只剩下2个container。我们依次测试是哪个镜像里包含libcrypto3。可以看到alpine的pod有3个副本.

Q先生 657

Hikari默认配置

springboot默认使用的是hikari连接池,常用配置。

demon7552003的小本本 2077

32、生物信息学中的符号、缩写及相关概念解析

本文详细解析了生物信息学中常用的符号、缩写及相关概念,涵盖概率理论、函数表示、模型结构、图与集合、维度参数、神经网络、隐藏马尔可夫模型、双向架构、语法系统、系统发育树、微阵列分析以及核方法与支持向量机等多个领域。通过表格和mermaid流程图的形式,系统梳理了各类符号的定义与应用场景,并介绍了常见缩写的全称与意义。文章旨在帮助研究人员准确理解生物信息学中的基础术语,提升对基因表达分析、序列建模、机器学习等技术的理解与应用能力。

rrr55的博客 148

hikariconfig mysql_HikariConfig配置详解

SpringBoot 2.0 开始推 HikariCP ,将默认的数据库连接池从 tomcat jdbc pool 改为了 hikari , HikariCP 在性能和并发方面确实表现不俗(号称最快的连接池)。如果你使用 spring-boot-starter-jdbc 或 spring-boot-starter-data-jpa ,会自动添加对 HikariCP 的依赖,也就是说此时使用 Hik...

weixin_42449583的博客 802

【FPGA教程案例89】编译码2——使用vivado核实现RS信道编译码

RS编码,又称里所码,即Reed-solomon codes,是一种前向纠错的信道编码,对由校正过采样数据所产生的多项式有效。当接收器正确的收到足够的点后,它就可以恢复原来的多项式,即使接收到的多项式上有很多点被噪声干扰失真。

FPGA/MATLAB学习教程/源码/项目合作开发 3545

Unity 面试篇|(四)Unity性能优化篇 【全面总结 | 持续更新】

Unity中,CPU准备好需要绘制的元素,对底层图形程序接口进行调用的过程,每次引擎准备数据并通知GPU的过程称为一次Draw Call。DrawCall越高对显卡的消耗就越大。降低DrawCall的方法:动态合批静态合批降低shader的等级特性场景优化策略——遮挡技术。rectMask2D替代Mask。

游戏开发小Y的博客 13万+

批量插入导致数据库连接异常java.sql.SQLTransientConnectionException

1,背景: 这是一个解析Txt 保存更新内容接口 /** * analysis txt,insert every line content but except first line */ @PostMapping("txt") @Transactional(rollbackFor = Exception.class) @ApiOperation(value = "解析接口") @ApiImplicitParams({ @ApiI

fudaolai的博客 7419

【即插即用模块】注意力篇 | TGRS 2025 | MFA聚特征+HPDown保细节+HFF融层级,三大模块各司其职,性能翻倍!

本文介绍了MTMLNet网络中的三大核心模块:MFA(多阶段特征聚合)、HPDown(混合池化下采样)和HFF(分层特征融合)。MFA通过双尺度深度卷积和注意力机制增强特征提取能力;HPDown结合平均池化和最大池化,有效保留下采样过程中的特征信息;HFF采用三注意力机制实现自适应特征融合。这三个模块协同工作,在红外小目标检测与分割任务中取得了SOTA效果。实验表明,各模块在特征提取、信息保留和融合方面均优于传统方法,可灵活应用于各类视觉任务中。

主要更新底层视觉(去噪、超分等)相关的科研内容,形式为【论文精读】+【论文复现】 287

浙大java60001_SQLTransientConnectionException: Connection is not available, request timed out after 6...

数据源使用的是Hikari ,但是 在运行一段时间后爆:SQLTransientConnectionException: Connection is not available, request timed out after 60001ms.配置超时确实是 配置了 60s 超时。百度一般都说是什么配置问题,会不会是配置问题?dataSource.setReadOnly(false); //默...

weixin_39906358的博客 2819

MFC C++ 中实现跨平台(WindowsLinux)的远程桌面控制

**输入捕获**:在显示窗口中捕获鼠标/键盘事件(重写 `OnLButtonDown`、`OnMouseMove`、`OnKeyDown` 等),将事件坐标/键值通过网络发送到服务端。- **显示窗口**:使用 `CStatic` 或自定义 `CWnd` 派生类显示远程桌面图像(通过 `StretchDIBits` 绘制解压后的像素数据)。// 转换为相对坐标。- **Wayland 支持**:需使用 `libweston` 或 `xdg-desktop-portal`,较复杂,建议优先支持 X11。

寒寒豆豆软件公司的博客 157

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

MySQLNonTransientConnectionException: No operations allowed after connection closed

原因分析查看了Mysql的文档,以及Connector/J的文档以及在线说明发现,出现这种异常的原因是:  Mysql服务器默认的“wait_timeout”是8小时,也就是说一个connection空闲超过8个小时,Mysql将自动断开该connection。这就是问题的所在,在C3P0 pools中的connections如果空闲超过8小时,Mysql将其断开,而C3P0并不知道该connec...

xiang__liu的博客 1303

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

SpringBoot使用HikriCP数据源连接池整合Mybatis,MappperXML和Mapper注解混用版

笔者在 SpringBoot使用HikriCP数据源连接池整合Mybatis,MappperXML版和SpringBoot使用HikriCP数据源连接池整合Mybatis,Mappper注解版中分别展示了mybatis注解版和XML如何和SpringBoot整合。 今天笔者就来演示混用版的使用,其实混用版就是在XML版直接用注解就好。 数据源pom.xml文件配置、application.pr...

a907691592的博客 954

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

lwip-2.0.3

lwip是瑞典计算机科学院(SICS)的Adam Dunkels 开发的一个小型开源的TCP/IP协议栈。实现的重点是在保持TCP协议主要功能的基础上减少对RAM 的占用。

数据库连接超时的处理

Caused by: java.sql.SQLTransientConnectionException: HikariPool-1 - Connection is not available, request timed out after 30000ms.

a275870703的博客 4397

hiricacp 连接池校验机制

我知道hikaricp获取连接之后会校验连接的有效性,就猜想如果校验失败了,那本次请求是不是就是失败了,如果这样的话,那就没校验的意义了,所以肯定有重试机制用以保证请求的完整性。项目发生告警,但是并没有影响业务,看了下日志,红框里面有循环调用了3次 ,一直以为是外部的重试在重试,但是外部确没有重试记录,就深扒了代码。这里面调用了 result.getConnection();result为hikariPool。elapsedMillis 方法是将当前时间戳-startTime 得出的时间差。

soldier_jw的博客 933

mysql SQLNonTransientConnectionException 异常分析处理

这里写自定义目录标欢迎使用Markdown编辑器新的改变功能快捷键合理的创建标题,有助于目录的生成如何改变文本的样式插入链接与图片如何插入一段漂亮的代码片生成一个适合你的列表创建一个表格设定内容居中、居左、居右SmartyPants创建一个自定义列表如何创建一个注脚注释也是必不可少的KaTeX数学公式新的甘特图功能,丰富你的文章UML 图表FLowchart流程图导出与导入导出导入 欢迎使用Markdown编辑器 你好! 这是你第一次使用 Markdown编辑器 所展示的欢迎页。如果你想学习如何使用Mark

卡洛~carlo的博客 2万+

数据库连接池hikari异常断开解决思路(整理的网上的资料)

数据库连接池连接超时异常断开的问题。提出以下解决思路 1.延长maxLifetime大小 注:maxLifetime设置一个connection在连接池中的存活时间 默认30分钟 ,如果设置为0,表示存活时间无限大。如果不等于0且小于30秒则会被重置回30分钟。 2.更改配置allowPoolSuspension: true registerMbeans: true 效果当池被暂停时,调用 getConnection()将不会...

mianhuabushitang的博客 1万+

连接池 HikariPool (二) - 获取及关闭连接

HikariPool 数据库连接池 连接池的获取及归还 多线程并发

weixin_44612246的博客 6205

HikariPool-1 - Exception during pool initialization.的解决方法

HikariPool-1 - Exception during pool initialization.的解决方法。 HikariPool-1-池初始化期间出现异常。 1.在application.properties中的spring.datasource.url后增加一个&amp;useSSL=false&amp;serverTimezone=UTC。 #配置数据源 spring.datas...

LYly_B的博客 2万+
上一篇: 一起来学 SpringBoot 2.x | 第七篇:整合 Mybatis
下一篇: 几个大型网站的Feeds(Timeline)设计简单对比
公众号-芋道源码
博客等级 码龄10年 1639粉丝 377原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值