萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 資料庫 >> MySQL 教學

MySQL 連接數負載能力優化:從參數調優到架構層面解決方案

連接數瓶頸現象

  • 報錯:ERROR 1040 (HY000): Too many connections
  • 現象:QPS 未高但連接數飆升、新連接建立緩慢、CPU 尖峰在線程切換。

核心參數速覽與調優策略

參數 預設值 建議調整 生效方式 風險提示
max_connections 151 (8.0) / 100 (5.7) 機器記憶體/線程棧估算,典型 500-3000 動態 SET GLOBAL 或配置文件 過大導致 OOM,需配合 thread_stack、sort_buffer_size 估算
max_user_connections 0 (無限制) 單用戶上限 500-1000,防單租戶佔滿 動態 合理限流,避免誤傷正常高併發用戶
thread_cache_size 自動(基於 max_connections) 100-200,減少線程創建銷毀開銷 動態 無顯著風險
wait_timeout 28800 (8h) 300-600 秒,配合應用心跳 動態 過小導致批次任務斷連
interactive_timeout 28800 同 wait_timeout 動態 同上
innodb_thread_concurrency 0 (無限制) 高併發時設 16-64,配合 innodb_adaptive_max_sleep_delay 動態 設過小限制吞吐,設過大退化為無限制
innodb_stats_on_metadata ON 設 OFF (0),避免 information_schema 查詢觸發統計掃描 動態 統計資訊更新延遲,可接受

動態調整實戰

-- 緊急擴容連接數(無需重啟)
SET GLOBAL max_connections = 2000;
SET GLOBAL max_user_connections = 800;
SET GLOBAL wait_timeout = 300;
SET GLOBAL innodb_thread_concurrency = 32;
SET GLOBAL innodb_stats_on_metadata = 0;

-- 持久化寫入配置文件
vim /etc/my.cnf
[mysqld]
max_connections = 2000
max_user_connections = 800
wait_timeout = 300
innodb_thread_concurrency = 32
innodb_stats_on_metadata = 0
thread_cache_size = 200

連接池層面優化(應用端)

HikariCP 黃金配置

spring:
  datasource:
    hikari:
      maximum-pool-size: 30           # 業務峰值 QPS * 平均RT(秒) * 1.5
      minimum-idle: 10
      idle-timeout: 300000            # 5分鐘
      max-lifetime: 1800000           # 30分鐘
      connection-timeout: 30000
      validation-timeout: 5000
      leak-detection-threshold: 60000
      pool-name: HikariCP-MySQL

關鍵原則

  • 連接池大小 ≈ CPU 核心數 × (1 + 平均等待時間/平均服務時間),而非單純設大。
  • 啟用 leakDetectionThreshold 監控洩漏。
  • 使用 SELECT 1 或 /* ping */ 健康檢查,避免 MySQL 端 wait_timeout 斷開導致借出失效連接。

架構層面解耦(治本)

  1. 讀寫分離:主庫寫、從庫讀,分散連接壓力。
  2. 引入 ProxySQL:連接多路複用、查詢路由、熔斷限流、SQL 重寫。
  3. 熱點數據下沉 Redis:高頻點查繞過 MySQL,連接需求降 80%+。
  4. 異步寫入:MQ 削峰填谷,寫入連接平滑化。
  5. 分庫分表:單表連接壓力物理隔離。

監控與告警體系

# 關鍵指標
Threads_connected / max_connections > 80%  → 告警
Threads_running / Threads_connected > 50%  → 高並發活躍,關注慢查詢
Aborted_connects 快速增長              → 應用連接風暴或網絡抖動
Connection_errors_internal / max_connections  → 內部錯誤導致連接失敗

Linux 系統層面配合

/etc/security/limits.conf
mysql soft nofile 65535
mysql hard nofile 65535

/etc/sysctl.conf
net.core.somaxconn = 65535
net.ipv4.tcp_max_syn_backlog = 65535
fs.file-max = 1000000

sysctl -p

總結:分層治理清單

層級 動作 優先級 見效速度
應用連接池 適配業務模型、啟用洩漏檢測、健康檢查 P0 即時
MySQL 參數 max_connections、wait_timeout、thread_cache、innodb_thread_concurrency P0 動態即時
架構演進 讀寫分離、ProxySQL、Redis 下沉、異步化、分庫分表 P1 中長期
OS 限制 ulimit、somaxconn、tcp_backlog P1 重啟生效
copyright © 萬盛學電腦網 all rights reserved