You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

高并发场景下JDBC连接超时无法处理请求问题排查

解决高并发下JDBC连接超时(Connection reset by peer)问题

问题核心

高并发场景下系统无法处理后续请求,抛出JDBC连接异常,根源是MySQL主动断开了连接池中长期空闲的连接,但连接池未检测到连接失效,分配无效连接后触发通信错误,最终耗尽所有有效连接。关键报错信息:

Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: The last packet successfully received from the server was 820,677 milliseconds ago.  The last packet sent successfully to the server was 820,679 milliseconds ago. is longer than the server configured value of 'wait_timeout'. You should consider either expiring and/or testing connection validity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection property 'autoReconnect=true' to avoid this problem.
Caused by: java.net.SocketException: Connection reset by peer: socket write error

解决方案

  • 配置连接池有效性检测
    给连接池添加连接校验逻辑,确保分配连接前验证其可用性,无效则销毁重建。以主流连接池为例:

    • HikariCP:在配置文件中添加
      connection-test-query=SELECT 1
      validation-timeout=5000
      idle-timeout=27000000  # 设为7.5小时,需小于MySQL的wait_timeout值
      
    • Tomcat JDBC:添加
      validationQuery=SELECT 1
      testOnBorrow=true
      testWhileIdle=true
      timeBetweenEvictionRunsMillis=3600000  # 每小时检测一次空闲连接
      
  • 调整MySQL超时参数
    增大wait_timeout和interactive_timeout(两者需保持一致),避免MySQL过早断开空闲连接:

    • 临时生效(重启MySQL后失效):
      SET GLOBAL wait_timeout = 86400;
      SET GLOBAL interactive_timeout = 86400;
      
    • 永久生效:修改MySQL配置文件(my.cnf/my.ini),添加以下配置后重启服务:
      wait_timeout=86400
      interactive_timeout=86400
      

    注意:参数值不宜过大,否则会导致MySQL保留过多空闲连接,占用系统资源。

  • 排查并修复连接泄漏
    检查代码中数据库会话/连接的释放逻辑,确保所有获取的连接都被正确关闭。比如Hibernate中使用try-with-resources自动关闭Session:

    try (Session session = sessionFactory.openSession()) {
        // 执行数据库操作
    } catch (HibernateException e) {
        // 异常处理
    }
    

    连接泄漏会在高并发下快速耗尽连接池,是此类问题的常见诱因,必须彻底排查修复。

  • 临时应急方案(不推荐长期使用)
    在JDBC URL中添加autoReconnect=true参数,让驱动自动重连失效连接:

    jdbc:mysql://localhost:3306/your_db?autoReconnect=true&failOverReadOnly=false
    

    该方案可能引发事务一致性问题,仅作为临时缓解手段,不能替代前面的规范配置。

内容的提问来源于stack exchange,提问作者Aniket Gupta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 17:02:44