首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫

MySQL Binlog 遠程實時備份:mysqlbinlog 5.6+ 實時拉取 + 自動重連腳本

     編輯:MySQL 資料庫相關知識

痛點

  • 傳統定時備份有窗口期丟失風險
  • 無法備份正在寫入的活躍 Binlog

MySQL 5.6+ 方案:mysqlbinlog 實時拉取

mysqlbinlog --read-from-remote-server --raw --stop-never \
  --host=192.168.244.145 --port=3306 --user=repl --password=repl \
  mysql-bin.000001

原理:模擬 Slave,走 Replication API 實時獲取事件,延遲 0.5-1s。

關鍵參數

  • --raw:二進制存儲,每 4K 刷盤
  • --stop-never:持續跟隨,不退出
  • --result-file=/backup/prefix-:本地文件前綴
  • --stop-never-slave-server-id:指定偽裝 server-id

缺陷與解決:斷線不自動重連

Shell 死循環腳本:檢測進程退出 → 睡 10s → 從本地最新 Binlog 續傳 → 記錄日誌。

while :; do
  LAST_FILE=$(ls -t $DIR | head -1)
  mysqlbinlog --raw --read-from-remote-server --stop-never ... $LAST_FILE
  echo "$(date) exited, code $?" >> log
  sleep 10
done

注意事項

  • --raw 時內存緩衝 4K 刷盤,斷連即時落盤
  • 無 --raw 時文本模式須指定具體文件名,實時落盤
  • Relay Log 是實時寫盤,mysqlbinlog 預設批量刷盤
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved