傳統 SHOW SLAVE STATUS 中的 Seconds_Behind_Master 受 SQL 線程阻塞、長事務等影響,精度低且易誤報。Percona Toolkit 中的 pt-heartbeat 採用主動心跳寫入 + 從庫時間戳對比機制,提供秒級精準的延遲監控。
heartbeat 表寫入當前時間戳 NOW()time() 系統時間,差值即為延遲要求:主從系統時鐘同步(NTP),否則結果無參考價值。
# 心跳表結構(自動創建)
CREATE TABLE `heartbeat` (
`ts` VARCHAR(26) NOT NULL,
`server_id` INT UNSIGNED NOT NULL PRIMARY KEY,
`file` VARCHAR(255) DEFAULT NULL,
`position` BIGINT UNSIGNED DEFAULT NULL,
`relay_master_log_file` VARCHAR(255) DEFAULT NULL,
`exec_master_log_pos` BIGINT UNSIGNED DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
pt-heartbeat --update \
-h 192.168.244.10 -u monitor -p monitor123 \
-D test --create-table --daemonize --interval 1
--update:更新模式,互斥於 --monitor/--check--create-table:首次運行自動建表--daemonize:後台守護進程運行--interval 1:每秒更新一次(默認 1s)pt-heartbeat --monitor \
-h 192.168.244.20 -u monitor -p monitor123 \
-D test --master-server-id=1 --frames 1m,5m,15m
輸出格式:
10061.00s [ 167.68s, 33.54s, 11.18s ]
10062.00s [ 335.38s, 67.08s, 22.36s ]
# 當前延遲 [ 1分鐘平均, 5分鐘平均, 15分鐘平均 ]
pt-heartbeat --check \
-h 192.168.244.20 -u monitor -p monitor123 \
-D test --master-server-id=1
# 輸出單一數值:10039.00
pt-heartbeat --check --recurse 2 \
-h 192.168.244.20 -u monitor -p monitor123 \
-D test --master-server-id=1
# 輸出各層從庫延遲:
# 192.168.244.30:3306 5.20
# 192.168.244.40:3306 8.70
| 參數 | 說明 | 典型值 |
|---|---|---|
--master-server-id | 指定主庫 server_id,監控/檢查模式必填 | 1 |
--skew | 檢查相對更新的延遲補償,默認 0.5s | 0.5 |
--frames | 移動平均時間窗口,逗號分隔 | 1m,5m,15m |
--utc | 使用 UTC 時間,避免時區差異(主從必須一致) | 建議啟用 |
--replace | 更新模式使用 REPLACE 而非 UPDATE,防止表被清空後不再寫入 | 建議啟用 |
--file | 監控輸出寫入文件(配合 --daemonize) | /var/log/pt-heartbeat.log |
--config | 參數文件路徑(命令行首參),格式:option=value | /etc/pt-heartbeat.conf |
# /etc/pt-heartbeat.conf
host=192.168.244.20
user=monitor
password=monitor123
monitor
database=test
master-server-id=1
utc
frames=1m,5m,15m
file=/var/log/pt-heartbeat.log
啟動:pt-heartbeat --config /etc/pt-heartbeat.conf
# Perl 核心計算邏輯
my ($ts, $hostname, $server_id) = $sth->fetchrow_array();
my $now = time; # 系統時間戳
my $delay = $now - unix_timestamp($ts) - $skew; # 減去心跳時間與補償
$delay = 0.00 if $delay < 0; # 負值歸零
--skew 目的:Master 寫入時間為整秒(如 10:00:00.000),Slave 讀取需網絡傳輸,預留 0.5s 容差避免誤報 1s 延遲。
GRANT REPLICATION CLIENT, SELECT, INSERT, UPDATE ON `test`.`heartbeat` TO 'monitor'@'%' IDENTIFIED BY 'xxx';[Unit]
Description=pt-heartbeat Master Updater
After=network.target mysql.service
[Service]
Type=forking
ExecStart=/usr/bin/pt-heartbeat --update -h 127.0.0.1 -u monitor -p xxx -D test --create-table --daemonize --interval 1 --replace --utc
Restart=always
[Install]
WantedBy=multi-user.target
--check 模式配合 node_exporter textfile collectordelay > 10s 警告,> 60s 致命The --master-server-id option must be specified:心跳表使用 server_id 區分主庫,監控端必須顯式指定--replace 確保記錄自動重建pt-heartbeat --update 進程,指定不同 server_idpt-heartbeat 是目前生產環境監控 MySQL 複製延遲最可靠的工具,建議納入標準化監控體系。