萬盛學電腦網

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

MySQL 主從同步配置極簡入門指南

架構圖解

Master (192.168.1.1)  --binlog-->  Slave (192.168.1.2)
  server-id=1                    server-id=2
  log-bin=mysql-bin              read-only=1 (建議)
  binlog-do-db=powerdns          replicate-do-db=powerdns (可選)

Master 配置 /etc/my.cnf

[mysqld]
server-id = 1
log-bin = mysql-bin
binlog-do-db = powerdns          # 只同步指定庫,省資源
binlog-ignore-db = mysql         # 忽略系統庫
expire_logs_days = 7             # 自動清理舊 binlog
max_binlog_size = 100M

建立同步帳號

GRANT REPLICATION SLAVE ON *.* TO 'repl_user'@'192.168.1.%' IDENTIFIED BY 'StrongPass123!';
FLUSH PRIVILEGES;

獲取 Master 同步座標

FLUSH TABLES WITH READ LOCK;   -- 短暫鎖表,確保一致性座標
SHOW MASTER STATUS;
+------------------+----------+--------------+------------------+
| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+----------+--------------+------------------+
| mysql-bin.000004 |      106 | powerdns     | mysql            |
+------------------+----------+--------------+------------------+
UNLOCK TABLES;

記住 File 與 Position,後續 Slave 配置需用到。

Slave 配置 /etc/my.cnf

[mysqld]
server-id = 2
log-bin = mysql-bin            # 從庫也開 binlog,支援級聯/備份
relay-log = relay-bin
read-only = 1                  # 防止誤寫入
replicate-do-db = powerdns     # 可選,與 Master 對應

啟動同步

CHANGE MASTER TO
  MASTER_HOST='192.168.1.1',
  MASTER_USER='repl_user',
  MASTER_PASSWORD='StrongPass123!',
  MASTER_PORT=3306,
  MASTER_LOG_FILE='mysql-bin.000004',
  MASTER_LOG_POS=106;

START SLAVE;

驗證同步狀態

SHOW SLAVE STATUS\G
*************************** 1. row ***************************
               Slave_IO_Running: Yes
              Slave_SQL_Running: Yes
           Seconds_Behind_Master: 0
                Last_IO_Error:
               Last_SQL_Error:
...

關鍵指標:Slave_IO_Running=Yes(I/O 線程連接正常)、Slave_SQL_Running=Yes(SQL 線程執行正常)、Seconds_Behind_Master=0(無延遲)。

常見故障與處理

現象原因處理
IO_Running=No, Last_IO_Error: Access denied帳號/密碼/IP 錯誤核對 GRANT 主機、密碼、防火牆
IO_Running=No, Last_IO_Error: timeout網路不通/防火牆telnet master 3306、安全組放行
SQL_Running=No, Last_SQL_Error: Duplicate entry主鍵衝突/手動寫入從庫跳過錯誤 SET GLOBAL sql_slave_skip_counter=1; START SLAVE; 或重建從庫
Seconds_Behind_Master 持續增長從庫寫入慢/大事務/硬體瓶頸優化從庫索引、參數、升級硬體、並行複製

維護建議

  • 監控 Slave_IO_Running/Slave_SQL_Running/Seconds_Behind_Master,異常即時告警。
  • 定期 CHECKSUM TABLE 或 pt-table-checksum 驗證主從資料一致性。
  • 備份從庫(xtrabackup 或 mysqldump --single-transaction --master-data=2),不影響主庫效能。
  • GTID 模式 (MySQL 5.6+) 更簡單:CHANGE MASTER TO MASTER_AUTO_POSITION=1,無需手動指定 File/Position。

總結

主從同步核心四步:**Master 開 binlog + 建帳號 → 記錄座標 → Slave 設定 CHANGE MASTER → START SLAVE 驗證**。生產環境務必加上 read-only、GTID、半同步複制、監控告警 四大保障。

copyright © 萬盛學電腦網 all rights reserved