首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫

MySQL "Lost connection to MySQL server during query" 排查思路:網絡、超時、大包、服務器端異常全維度分析

     編輯:MySQL 資料庫相關知識

錯誤含義

客戶端與 Server 之間的 TCP 連接在查詢執行過程中意外斷開,非正常關閉(如 mysql_close())。

常見原因與排查清單

類別具體原因排查/解決
網絡/連接層防火牆/網關空閒超時切斷長連接啟用客戶端/連接池 autoReconnect=true、心跳機制;調整防火牆超時
客戶端 wait_timeout/interactive_timeout 過小Server 默認 8h,若修改過請檢查;連接池配置 testOnBorrow + validationQuery
網絡抖動、交換機/路由器故障Ping/TCping 監控、抓包分析
查詢/數據層單條 SQL 執行時間超過 net_read_timeout/net_write_timeout(默認 30s/60s)優化慢查詢、加索引、分頁、拆分大事務;調大超時參數
結果集過大,超過 max_allowed_packet(默認 4MB/64MB)增大 max_allowed_packet(Server 與 Client 同調);分批獲取
Blob/Text 大字段讀取慢避免 SELECT *,按需選列;啟用壓縮協議
服務器端異常OOM Killer 殺死 mysqld 進程檢查 /var/log/messages Out of memory;調整 innodb_buffer_pool_size、限制連接數
mysqld 崩潰重啟查看錯誤日志 .err,搜索 Assertion failure、Signal 11 等

快速定位步驟

  1. 查看客戶端異常堆棧:是讀超時、寫超時、還是連接重置?
  2. 對比時間點,檢查 Server 錯誤日志是否有同期崩潰/重啟記錄。
  3. 執行 SHOW GLOBAL STATUS LIKE 'Aborted_connects'; 觀察計數增長。
  4. 抓包確認是否收到 FIN/RST 包及發送方。

預防性配置建議

  • 連接池:testOnBorrow=true、validationQuery=SELECT 1、eviction 定期清理空閒連接。
  • JDBC URL:?autoReconnect=true&failOverReadOnly=false&maxReconnects=3。
  • Server:wait_timeout=28800、net_read_timeout=60、net_write_timeout=60、max_allowed_packet=64M。
  • 監控:Prometheus + mysqld_exporter 監控 Threads_connected、Aborted_clients、Max_used_connections。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved