資料庫維護不應等到故障發生才被動應對。本系列首篇建立**預防性維護體系**:定期備份+Binlog、定期巡檢、啟動期自動修復,並提供從簡單到健壯的巡檢腳本範本,奠定無人值守運維基石。
排程工具:Windows 用「計劃任務」,Linux/Unix 用 cron(以運行 MySQL 的系統用戶 mysql 的 crontab 執行)。
mysql 系統用戶身份運行,避免檔案擁有權污染。myisamchk --silent --fast:--silent (-s) 僅報錯,配合 Cron 郵件機制「無錯不郵件」。--fast (-C) 僅檢查上次檢查後被修改的表,大幅縮短耗時。find | xargs 解決大量表通配符參數溢位。#!/bin/sh
# 簡單巡檢
cd /usr/local/mysql/var
myisamchk --silent --fast */*.MYI
isamchk --silent */*.ISM
#!/bin/sh
# /usr/local/mysql/bin/check_tables
DATADIRS="/usr/local/mysql/var /data/mysql2/var"
for DATADIR in $DATADIRS; do
if [ -d "$DATADIR" ]; then
find "$DATADIR" -name '*.MYI' -print | xargs /usr/local/mysql/bin/myisamchk --silent --fast
find "$DATADIR" -name '*.ISM' -print | xargs /usr/local/mysql/bin/isamchk --silent
fi
done
su - mysql 切換專用用戶。vi /usr/local/mysql/bin/check_tables 編寫腳本(選健壯版)。chmod +x /usr/local/mysql/bin/check_tables 賦予執行權限。/usr/local/mysql/bin/check_tables 手工測試,確認無語法錯誤、無誤報。crontab -e 加入排程,例:0 3 * * 0 /usr/local/mysql/bin/check_tables(每週日 03:00)。| 啟動體系 | 整合方式 | 關鍵點 |
|---|---|---|
| BSD / rc.local | 在 mysqld 啟動命令前插入 myisamchk -s -r | 簡單、通用、Linux 兼容佳 |
| System V / rc.d | 建立獨立 S19mysql.check 腳本,chkconfig 管理 | 標準、可控、順序明確 |
| systemd (現代) | 建立 mysql-check.service,Before=mysqld.service | 原生、依賴關係聲明式、日誌整合 |
核心參數:myisamchk -s -r(靜默 + 自動修復),配合 myisam_recover_options=BACKUP,FORCE 雙保險。
log_bin 已啟用、expire_logs_days 設定合理。check_tables 健壯版腳本至 /usr/local/mysql/bin/。mysql 用戶建立 cron 週巡檢任務。