萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 資料庫 >> MySQL 教學

MySQL 雙機熱備 (主從複制) 完整配置指南:版本要求、my.cnf、授權、備份、啟動、驗證、日誌清理

MySQL 原生非同步主從複制實現雙機熱備。版本要求:雙邊 ≥ 3.23,Slave 版本 **≥ Master 版本**。核心機制:Master 寫 Binlog → Slave I/O 線程拉取寫 Relay Log → SQL 線程重放。

1. Master 配置 (my.cnf / my.ini)

[mysqld]
server-id = 1                    # 唯一,1~2^32-1
log-bin = mysql-bin              # 啟用二進制日誌
binlog-do-db = db_name           # 僅記錄指定庫 (可選,多庫用逗號)
binlog-ignore-db = mysql,test    # 不記錄的庫 (可選)
sync_binlog = 1                  # 每次提交刷盤,最安全
innodb_flush_log_at_trx_commit = 1

重啟 MySQL:systemctl restart mysqld

2. 建立複制專用帳號

GRANT REPLICATION SLAVE ON *.* TO 'repl'@'%' IDENTIFIED BY 'slavepass';
FLUSH PRIVILEGES;

5.0.2 以前版本用 GRANT FILE ON *.* ... (不建議使用舊版)。

3. 鎖定 Master、備份、記錄座標、解鎖

-- 1. 鎖表 (阻寫入)
FLUSH TABLES WITH READ LOCK;

-- 2. 記錄 Binlog 座標
SHOW MASTER STATUS\G;
-- 記下 File (如 mysql-bin.000003) 和 Position (如 73)

-- 3. 備份資料 (推薦物理複製 data 目錄,或 mysqldump --master-data=2)
tar czf /backup/master_data.tar.gz /var/lib/mysql/dbname

-- 4. 解鎖
UNLOCK TABLES;

4. Slave 配置 (my.cnf)

[mysqld]
server-id = 2                    # 必須不同於 Master
master-host = 192.168.1.10       # Master IP
master-port = 3306
master-user = repl
master-password = slavepass
master-connect-retry = 60        # 重試間隔秒
report-host = slave-host         # 可選,供 SHOW SLAVE HOSTS 顯示
relay-log = slave-relay-bin      # 建議顯式指定

重啟 Slave MySQL 服務。

5. 載入備份資料到 Slave

解壓縮備份檔到 Slave 資料目錄,或用 mysql < backup.sql 匯入。

6. 配置 Slave 複制參數並啟動

CHANGE MASTER TO
    MASTER_HOST='192.168.1.10',
    MASTER_USER='repl',
    MASTER_PASSWORD='slavepass',
    MASTER_PORT=3306,
    MASTER_LOG_FILE='mysql-bin.000003',  -- 步驟 3 記錄的 File
    MASTER_LOG_POS=73,                   -- 步驟 3 記錄的 Position
    MASTER_CONNECT_RETRY=10;

START SLAVE;

7. 驗證複制狀態

SHOW SLAVE STATUS\G

-- 關鍵指標
Slave_IO_Running: Yes
Slave_SQL_Running: Yes
Seconds_Behind_Master: 0
Master_Log_File: mysql-bin.000003
Read_Master_Log_Pos: 73
Relay_Log_File: slave-relay-bin.000002
Relay_Log_Pos: 251

兩個 Yes + Seconds_Behind_Master=0 即成功。

8. 日誌清理操作 (Binlog 過大時)

-- Master 端
FLUSH TABLES WITH READ LOCK;
SHOW MASTER STATUS;  -- 記錄新 File/Position
UNLOCK TABLES;

-- Slave 端
STOP SLAVE;

-- Master 端 (確認 Slave 已處理完舊日誌後)
PURGE BINARY LOGS TO 'mysql-bin.000005';  -- 刪除此檔之前的所有日誌
-- 或 PURGE BINARY LOGS BEFORE '2024-01-01 00:00:00';

監控與維護建議

  • 監控 Seconds_Behind_Master、Slave_IO_Running、Slave_SQL_Running
  • 定期 CHECKSUM TABLE 或 pt-table-checksum 驗證資料一致性
  • GTID 模式 (5.6+) 簡化故障切換:CHANGE MASTER TO MASTER_AUTO_POSITION=1
  • 半同步複制 (rpl_semi_sync) 降低資料遺失風險
copyright © 萬盛學電腦網 all rights reserved