druid报错 discard long time none received connection

打印 上一主题 下一主题

主题 1031|帖子 1031|积分 3093

问题背景

在项目启动时出现大量

  c.a.d.pool.DruidAbstractDataSource: discard long time none received connection.
明显是Druid管理的数据库连接由于太长时间没有收到数据库发来的数据,把连接给回收掉了,这导致服务在启动时由于要重复创建连接让服务启动时间延长。
定位原因

根据错误信息,找到Druid源码
com.alibaba.druid.pool.DruidAbstractDataSource#testConnectionInternal(com.alibaba.druid.pool.DruidConnectionHolder, java.sql.Connection)
  1. if (validConnectionChecker != null) {
  2.         // 验证连接的有效性 mysql下实际调用代码在下面那块
  3.         boolean valid = validConnectionChecker.isValidConnection(conn, validationQuery, validationQueryTimeout);
  4.         long currentTimeMillis = System.currentTimeMillis();
  5.     if (holder != null) {
  6.         holder.lastValidTimeMillis = currentTimeMillis;
  7.         holder.lastExecTimeMillis = currentTimeMillis;
  8.     }
  9.     if (valid && isMySql) { // unexcepted branch
  10.         long lastPacketReceivedTimeMs = MySqlUtils.getLastPacketReceivedTimeMs(conn);
  11.         if (lastPacketReceivedTimeMs > 0) {
  12.             long mysqlIdleMillis = currentTimeMillis - lastPacketReceivedTimeMs;
  13.             if (lastPacketReceivedTimeMs > 0 //
  14.                     && mysqlIdleMillis >= timeBetweenEvictionRunsMillis) {
  15.                 discardConnection(holder);
  16.                 // 警告信息位置
  17.                 String errorMsg = "discard long time none received connection. "
  18.                         + ", jdbcUrl : " + jdbcUrl
  19.                         + ", version : " + VERSION.getVersionNumber()
  20.                         + ", lastPacketReceivedIdleMillis : " + mysqlIdleMillis;
  21.                 LOG.warn(errorMsg);
  22.                 return false;
  23.             }
  24.         }
  25.     }
  26.     // ... 省略
  27. }
  28. // com.alibaba.druid.pool.vendor.MySqlValidConnectionChecker#isValidConnection
  29.     public boolean isValidConnection(Connection conn, String validateQuery, int validationQueryTimeout) throws Exception {
  30.         if (conn.isClosed()) {
  31.             return false;
  32.         }
  33.         if (usePingMethod) {
  34.                 // 以ping的方式检测连接的有效性
  35.             if (conn instanceof DruidPooledConnection) {
  36.                 conn = ((DruidPooledConnection) conn).getConnection();
  37.             }
  38.             if (conn instanceof ConnectionProxy) {
  39.                 conn = ((ConnectionProxy) conn).getRawObject();
  40.             }
  41.             if (clazz.isAssignableFrom(conn.getClass())) {
  42.                 if (validationQueryTimeout <= 0) {
  43.                     validationQueryTimeout = DEFAULT_VALIDATION_QUERY_TIMEOUT;
  44.                 }
  45.                 try {
  46.                     ping.invoke(conn, true, validationQueryTimeout * 1000);
  47.                 } catch (InvocationTargetException e) {
  48.                     Throwable cause = e.getCause();
  49.                     if (cause instanceof SQLException) {
  50.                         throw (SQLException) cause;
  51.                     }
  52.                     throw e;
  53.                 }
  54.                 return true;
  55.             }
  56.         }
  57.         String query = validateQuery;
  58.         if (validateQuery == null || validateQuery.isEmpty()) {
  59.                 // 以 sql SELECT 1 的方式验证连接有效性
  60.             query = DEFAULT_VALIDATION_QUERY;
  61.         }
  62.         Statement stmt = null;
  63.         ResultSet rs = null;
  64.         try {
  65.             stmt = conn.createStatement();
  66.             if (validationQueryTimeout > 0) {
  67.                 stmt.setQueryTimeout(validationQueryTimeout);
  68.             }
  69.             rs = stmt.executeQuery(query);
  70.             return true;
  71.         } finally {
  72.             JdbcUtils.close(rs);
  73.             JdbcUtils.close(stmt);
  74.         }
  75.     }
  76. }
复制代码
这是调用 testConnectionInternal方法的上层.

可以看到,由于我们开启了testOnBorrow 开关,以是数据库连接会在申请乐成后,立即进行一次测试,然后根据数据库连接的最后一次心跳时间,判断是否闲置过长要丢弃掉该数据库连接。
该开关主要在从连接池获取时立即查抄连接的有效性。
而不开启testOnBorrow则会在保持连接过程中不断查抄连接的闲置环境,对闲置过长的连接回收。
com.alibaba.druid.util.MySqlUtils#getLastPacketReceivedTimeMs 这个方法会返回连接最后一次收到消息的时间.
  1. // 以mysql6的 com.mysql.cj.jdbc.ConnectionImpl 为栗子
  2. // getLastPacketReceivedTimeMs 方法中获取链接时间的实际方法
  3. public long getIdleFor() {
  4.      return this.lastQueryFinishedTime == 0 ? 0 : System.currentTimeMillis() - this.lastQueryFinishedTime;
  5. }
  6. // com.mysql.cj.NativeSession#execSQL
  7.     public <T extends Resultset> T execSQL(Query callingQuery, String query, int maxRows, NativePacketPayload packet, boolean streamResults,
  8.             ProtocolEntityFactory<T, NativePacketPayload> resultSetFactory, ColumnDefinition cachedMetadata, boolean isBatch) {
  9.         long queryStartTime = this.gatherPerfMetrics.getValue() ? System.currentTimeMillis() : 0;
  10.         int endOfQueryPacketPosition = packet != null ? packet.getPosition() : 0;
  11.         this.lastQueryFinishedTime = 0; // we're busy!
  12.         if (this.autoReconnect.getValue() && (getServerSession().isAutoCommit() || this.autoReconnectForPools.getValue()) && this.needsPing && !isBatch) {
  13.             try {
  14.                 ping(false, 0);
  15.                 this.needsPing = false;
  16.             } catch (Exception Ex) {
  17.                 invokeReconnectListeners();
  18.             }
  19.         }
  20.         try {
  21.             return packet == null
  22.                     ? ((NativeProtocol) this.protocol).sendQueryString(callingQuery, query, this.characterEncoding.getValue(), maxRows, streamResults,
  23.                             cachedMetadata, resultSetFactory)
  24.                     : ((NativeProtocol) this.protocol).sendQueryPacket(callingQuery, packet, maxRows, streamResults, cachedMetadata, resultSetFactory);
  25.         } catch (CJException sqlE) {
  26.             if (getPropertySet().getBooleanProperty(PropertyKey.dumpQueriesOnException).getValue()) {
  27.                 String extractedSql = NativePacketPayload.extractSqlFromPacket(query, packet, endOfQueryPacketPosition,
  28.                         getPropertySet().getIntegerProperty(PropertyKey.maxQuerySizeToLog).getValue());
  29.                 StringBuilder messageBuf = new StringBuilder(extractedSql.length() + 32);
  30.                 messageBuf.append("\n\nQuery being executed when exception was thrown:\n");
  31.                 messageBuf.append(extractedSql);
  32.                 messageBuf.append("\n\n");
  33.                 sqlE.appendMessage(messageBuf.toString());
  34.             }
  35.             if ((this.autoReconnect.getValue())) {
  36.                 if (sqlE instanceof CJCommunicationsException) {
  37.                     // IO may be dirty or damaged beyond repair, force close it.
  38.                     this.protocol.getSocketConnection().forceClose();
  39.                 }
  40.                 this.needsPing = true;
  41.             } else if (sqlE instanceof CJCommunicationsException) {
  42.                 invokeCleanupListeners(sqlE);
  43.             }
  44.             throw sqlE;
  45.         } catch (Throwable ex) {
  46.             if (this.autoReconnect.getValue()) {
  47.                 if (ex instanceof IOException) {
  48.                     // IO may be dirty or damaged beyond repair, force close it.
  49.                     this.protocol.getSocketConnection().forceClose();
  50.                 } else if (ex instanceof IOException) {
  51.                     invokeCleanupListeners(ex);
  52.                 }
  53.                 this.needsPing = true;
  54.             }
  55.             throw ExceptionFactory.createException(ex.getMessage(), ex, this.exceptionInterceptor);
  56.         } finally {
  57.                 // 需要开启数据库连接的jdbc参数 maintainTimeStats=true
  58.             if (this.maintainTimeStats.getValue()) {
  59.                     // 连接的最后查询时间被更新
  60.                 this.lastQueryFinishedTime = System.currentTimeMillis();
  61.             }
  62.             if (this.gatherPerfMetrics.getValue()) {
  63.                 ((NativeProtocol) this.protocol).getMetricsHolder().registerQueryExecutionTime(System.currentTimeMillis() - queryStartTime);
  64.             }
  65.         }
  66.     }
复制代码
办理

通过源码分析,就大抵清楚问题的原因。
druid会从数据库获取一批连接持有在当地,以便快速利用。
为了查抄连接的可用(如连接超时被数据库回收了,网络非常等),以是当开启testOnBorrow开关后,会在客户端从druid获取连接时进行闲置连接查抄。
而闲置查抄时比较连接当前时间与最后一次执行sql的时间的差值。
我们的服务在启动时没有进行数据查询,而且连接保活维持是通过ping的方式,以是当启动时间超过之前设置的15s后,再利用最开始池化的数据库借入连接时检测不外而抛出文章开头的非常信息。
我们可以通过调大闲置连接剔除时间和保活时间,让连接闲置能够撑过服务启动的无数据查询时间。
此外,假如服务的活泼环境很低,也就是执行sql的频率很低,可以设置环境变量druid.mysql.usePingMethod为false,让druid以执行SELECT 1sql的方式来保活连接,如此就会顺带刷新getLastPacketReceivedTimeMs属性。
  1. // com.alibaba.druid.pool.vendor.MySqlValidConnectionChecker#configFromProperties
  2.     public void configFromProperties(Properties properties) {
  3.         if (properties == null) {
  4.             return;
  5.         }
  6.         String property = properties.getProperty("druid.mysql.usePingMethod");
  7.         if ("true".equals(property)) {
  8.             setUsePingMethod(true);
  9.         } else if ("false".equals(property)) {
  10.             setUsePingMethod(false);
  11.         }
  12.     }
复制代码
当然通过源码尚有其他方式,可以自行发现。
  1. spring:
  2.         datasource:
  3.                 druid:
  4.                         # 让底层的jdbc维护连接的状态的时间
  5.                         url: jdck:mysql://xxx?maintainTimeStats=true
  6.                         # 连接闲置剔除时间
  7.                       time-between-eviction-runs-millis: 300000
  8.                       # 必须大于 time-between-eviction-runs-millis 时间
  9.                       keep-alive-between-time-millis: 450000
复制代码
  1.         // 启动代码添加系统属性
  2.         // 或者通过 -Ddruid.mysql.usePingMethod=false 的命令参数
  3.         // 或者通过环境变量
  4.     public static void main(String[] args) {
  5.         Properties properties = System.getProperties();
  6.         // 用 select 1 替换 ping 来检测连接保活
  7.         properties.setProperty("druid.mysql.usePingMethod", "false");
  8.         SpringApplication.run(App.class, args);
  9.     }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

惊雷无声

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表