面對數十上百個 MySQL 實例組成的集群,逐台登錄 SHOW SLAVE STATUS、SHOW MASTER STATUS 效率極低。本文介紹一個基於 Linux Shell 的輕量級監控工具 monrep,通過進程池並發采集、臨時文件隔離、兩秒刷新,實現集群級實時鳥瞰。
PID 命名臨時文件(/tmp/monrep_$PID_*),支持多會話並行運行。# 查看幫助
monrep -h
Usage: monrep [-d dbname]
-d Database Cluster name
-h Display basic help
# 監控名為 dbx 的集群
monrep -d dbx
#!/bin/bash
# monrep - MySQL Replication Cluster Monitor
# Author: skate
# Date: 2015/01/19
CLUSTER_NAME=$1
TMP_DIR="/tmp/monrep_$$" # PID 隔離
mkdir -p "$TMP_DIR"
# 1. 從配置文件/服務發現獲取集群主機列表
# 示例:hosts=("10.0.1.10" "10.0.1.11" "10.0.1.12")
get_cluster_hosts() {
# 實際可對接 CMDB、Consul、Etcd 或靜態文件
cat "/etc/monrep/clusters/${CLUSTER_NAME}.hosts"
}
# 2. 單主機采集函數(後台並發運行)
collect_host() {
local host=$1
local out_file="$TMP_DIR/${host}.out"
# SSH 免密執行采集命令,超時 5 秒
ssh -o ConnectTimeout=3 -o BatchMode=yes "$host" \
"mysql -e 'SHOW SLAVE STATUS\G; SHOW MASTER STATUS\G;'" > "$out_file" 2>&1
}
# 3. 進程池並發控制(固定 40 並發)
run_parallel() {
local hosts=($(get_cluster_hosts))
local max_jobs=40
local job_count=0
for host in "${hosts[@]}"; do
collect_host "$host" &
((job_count++))
if ((job_count >= max_jobs)); then
wait -n # 等待任意一個後台任務結束
((job_count--))
fi
done
wait # 等待所有剩餘任務
}
# 4. 聚合輸出渲染
render_dashboard() {
clear
echo "=== MySQL Cluster: $CLUSTER_NAME | $(date) ==="
printf "%-15s %-10s %-10s %-15s %-15s\n" "HOST" "IO_RUN" "SQL_RUN" "MASTER_LOG" "SEC_BEHIND"
for f in "$TMP_DIR"/*.out; do
host=$(basename "$f" .out)
io_run=$(grep -i "Slave_IO_Running" "$f" | awk '{print $2}')
sql_run=$(grep -i "Slave_SQL_Running" "$f" | awk '{print $2}')
master_log=$(grep -i "Master_Log_File" "$f" | awk '{print $2}')
sec_behind=$(grep -i "Seconds_Behind_Master" "$f" | awk '{print $2}')
printf "%-15s %-10s %-10s %-15s %-15s\n" "$host" "$io_run" "$sql_run" "$master_log" "$sec_behind"
done
}
# 主循環
trap "rm -rf $TMP_DIR; exit" INT TERM EXIT
while true; do
run_parallel
render_dashboard
sleep 2
done
ssh-copy-id)。mysql 客戶端(yum install mysql)。REPLICATION CLIENT 權限:GRANT REPLICATION CLIENT ON *.* TO 'monrep'@'%' IDENTIFIED BY 'password';/etc/monrep/clusters/dbx.hosts,每行一個 IP。SHOW GLOBAL STATUS 采集 QPS、Threads_connected、Innodb_buffer_pool_wait_free 等核心指標。Seconds_Behind_Master > 30 或 Slave_SQL_Running != Yes 發送郵件/鉚釘/企微。monrep 以「極簡依賴、極速部署、實時可見」解決了中小規模 MySQL 集群無監控平台時的可視化痛點,是 DBA 隨身工具箱的利器。