Percona Toolkit 是 MySQL 運維神器集,含 30+ 命令列工具。本文記錄安裝、核心工具用法與實戰輸出範例。
# CentOS/RHEL
yum install -y perl-DBD-MySQL perl-IO-Socket-SSL
rpm -ivh percona-toolkit-2.2.x.noarch.rpm
# Ubuntu/Debian
apt-get install -y libdbd-mysql-perl libio-socket-ssl-perl
dpkg -i percona-toolkit_2.2.x_all.deb
| 工具 | 用途 | 典型指令 |
|---|---|---|
| pt-query-digest | 慢查詢/一般查詢/二進制日誌/TCPdump 深度分析 | pt-query-digest slow.log --limit 20 |
| pt-online-schema-change | 線上無鎖變更表結構 (影子表+觸發器) | pt-online-schema-change --alter "ADD INDEX idx_c(c)" D=db,t=tbl --execute |
| pt-table-checksum | 主從資料一致性校驗 (基於 checksum) | pt-table-checksum h=master --replicate=percona.checksums |
| pt-table-sync | 主從資料同步 (修復不一致) | pt-table-sync --execute h=master h=slave --databases db |
| pt-archiver | 歸檔/刪除大量歷史資料 (分塊、不鎖表) | pt-archiver --source h=master,D=db,t=tbl --purge --where "created<'2022-01-01'" --limit 1000 |
| pt-kill | 殺掉符合條件的長查詢/閒置連線 | pt-kill --busy-time 60 --kill --print |
| pt-variable-advisor | 參數配置診斷建議 | pt-variable-advisor h=localhost -p'pwd' |
| pt-summary | 系統/硬體/OS/MySQL 總覽報表 | pt-summary |
| pt-mysql-summary | MySQL 實例配置/Schema/索引/大小統計 | pt-mysql-summary --user=root -p'pwd' |
| pt-deadlock-logger | 長期記錄死鎖到表 | pt-deadlock-logger --dest h=localhost,D=mon,t=deadlocks --user=mon -p'pwd' |
| pt-heartbeat | 高精度主從延遲監控 (秒級) | pt-heartbeat --update h=master --daemonize --create-table |
| pt-index-usage | 分析查詢索引使用 (需完整 slow_log) | pt-index-usage slow.log --user=root -p'pwd' |
| pt-visual-explain | EXPLAIN 輸出樹狀圖 | pt-visual-explain < query.sql |
# Rank Query ID Response time Calls R/Call V/M Item
# ==== ================== ============== ===== ======= ===== ====
# 1 0xABC123... 45.2% 12.3s 1500 0.008s 0.12 SELECT * FROM orders WHERE user_id=?
# 2 0xDEF456... 23.1% 6.3s 300 0.021s 0.45 UPDATE inventory SET qty=qty-1 WHERE sku=?
...
# Profile:
# Query 1: SELECT * FROM orders WHERE user_id=?
# Exec time: 12.3s total, 8.2ms avg, 1500 calls
# Lock time: 0.4s
# Rows examined: 4.5M (avg 3000)
# Rows sent: 1500
# Full scan: YES -> 需加索引 user_id
pt-online-schema-change 需目標表有 **主鍵或唯一索引**,否則報錯 Cannot find an ascendable indexpt-table-sync 目標庫必須預先建立相同 Schema,否則無法同步cpanm Module::Name 或 yum/apt 安裝對應 perl-* 套件Percona Toolkit 是 DBA 必備瑞士刀,**熟練 pt-query-digest + pt-online-schema-change + pt-table-checksum** 即可應對 90% 運維場景。