定期巡檢 MySQL 核心指標是 DBA 保障穩定性的基本功。本文解析一款實用的 Shell 巡檢腳本,涵蓋版本、進程數、客戶端連接數、QPS/TPS、Key Buffer/InnoDB Buffer/Query Cache 命中率等關鍵指標,並說明各指標計算邏輯、告警閾值與優化建議。
| 檢查項 | 核心指標 | 數據來源 | 健康閾值參考 |
|---|---|---|---|
| 版本 | 版本號 | SELECT @@version | 運行穩定版本(5.7/8.0 長期支持) |
| 進程 | mysqld 進程數 | ps -ef | grep mysql | ≥1(主從則 ≥2) |
| 連接數 | 當前客戶端連接 | SHOW PROCESSLIST | < max_connections × 80% |
| QPS | 每秒查詢數 | Questions / Uptime | 視業務而定,突增需告警 |
| TPS | 每秒事務數 | (Com_commit+Com_rollback) / Uptime | 同上 |
| Key Buffer 讀命中率 | 1 - Key_reads/Key_read_requests | SHOW GLOBAL STATUS | > 99%(MyISAM 核心) |
| Key Buffer 寫命中率 | 1 - Key_writes/Key_write_requests | 同上 | > 95% |
| InnoDB Buffer 讀命中率 | 1 - Innodb_buffer_pool_reads/Innodb_buffer_pool_read_requests | 同上 | > 99.9%(核心指標) |
| Query Cache 命中率 | Qcache_hits / (Qcache_hits+Qcache_inserts+Qcache_not_cached) | 同上 | MySQL 8.0 已移除 QC,5.7 視業務 |
# QPS 計算
qps_01="show global status like 'Questions';"
qps_02=$(mysql ... -e "$qps_01" | awk 'NR==2 {print $2}')
qps_03=$(cat /proc/uptime | awk '{print $1}') # 系統運行秒數
qps_04=$(awk "BEGIN {print $qps_02 / $qps_03}") # awk 支持浮點
# TPS 計算
tps_01="show global status like 'Com_commit';"
tps_02="show global status like 'Com_rollback';"
tps_sum=$((commit + rollback))
tps_avg=$(awk "BEGIN {print $tps_sum / $qps_03}")
# InnoDB Buffer 讀命中率
innob_01="show global status like 'Innodb_buffer_pool_reads';"
innob_02="show global status like 'Innodb_buffer_pool_read_requests';"
reads=$(mysql ... -e "$innob_01" | awk 'NR==2 {print $2}')
requests=$(mysql ... -e "$innob_02" | awk 'NR==2 {print $2}')
hit_rate=$(awk "BEGIN {print (1 - $reads/$requests) * 100}")
innodb_buffer_pool_size 是否足夠(建議物理內存 60%-75%)innodb_buffer_pool_instances 增加並發SHOW PROCESSLIST 找慢查詢sys.schema_table_statistics 定位高頻表max_connections,但需評估內存壓力key_buffer_sizeSELECT * FROM sys.statements_with_runtimes_in_95th_percentile LIMIT 10SHOW SLAVE STATUS\G 關注 Seconds_Behind_Masterpt-stalk 或 mysql-slow-log-analyzer 采集現場# 1. 放置路徑
/opt/mysql_monitor/check_mysql_health.sh
# 2. 權限
chmod +x check_mysql_health.sh
# 3. 專用監控用戶(最小權限)
CREATE USER 'monitor'@'%' IDENTIFIED BY 'xxx';
GRANT PROCESS, REPLICATION CLIENT, SELECT ON *.* TO 'monitor'@'%';
# 4. 定時任務(每 5 分鐘)
*/5 * * * * /opt/mysql_monitor/check_mysql_health.sh >> /var/log/mysql_health.log 2>&1
# 5. 告警集成(示例:企業微信/鉉釘 Webhook)
if (( $(echo "$hit_rate < 99" | bc -l) )); then
curl -X POST 'webhook_url' -d '{"msg":"InnoDB Buffer 命中率異常: '$hit_rate'%"}'
fi