複製架構核心:Master 寫 Binlog → Slave 讀 Relay Log → SQL 線程重放。版本原則:Master 版本 ≤ Slave 版本,Binlog 格式向前相容。
rep1 (10.0.0.1), Slave: rep2 (10.0.0.2)/usr/local/mysql, Datadir: /usr/local/mysql/datarepl/replpass
[mysqld]
server-id = 1
log-bin = mysql-bin
binlog-ignore-db = mysql # 不同步權限庫
# binlog-do-db = business_db # 僅同步指定庫 (二選一)
# 建立複製賬號
GRANT REPLICATION SLAVE ON *.* TO 'repl'@'rep2' IDENTIFIED BY 'replpass';
-- 若需 LOAD DATA FROM MASTER,額外授權:
GRANT FILE, SELECT, REPLICATION SLAVE ON *.* TO 'repl'@'rep2' IDENTIFIED BY 'replpass';
FLUSH PRIVILEGES;
# 方法 A:mysqldump 單線程 (小庫適用)
mysqldump --single-transaction --master-data=2 --all-databases > base.sql
# 方法 B:物理複製 (大庫、極速)
# 1. 加全局讀鎖
FLUSH TABLES WITH READ LOCK;
# 2. 另開終端打包數據目錄
tar czf /tmp/data.tar.gz /usr/local/mysql/data
# 3. 記錄 Binlog 位置
SHOW MASTER STATUS; -- 記下 File + Position
# 4. 解鎖
UNLOCK TABLES;
# 5. 傳輸解壓到 Slave,設置權限
[mysqld]
server-id = 2
master-host = rep1
master-user = repl
master-password = replpass
master-port = 3306
master-connect-retry = 60
replicate-ignore-db = mysql
replicate-do-db = business_db
relay-log = relay-bin
log-slave-updates = 1 # 鏈式複製必開
read-only = 1 # 防止誤寫入
-- Slave 導入基線數據後
CHANGE MASTER TO
MASTER_HOST='rep1',
MASTER_USER='repl',
MASTER_PASSWORD='replpass',
MASTER_LOG_FILE='mysql-bin.000001', -- 對應 SHOW MASTER STATUS
MASTER_LOG_POS=107;
START SLAVE;
SHOW SLAVE STATUS\G
-- 關鍵指標:
-- Slave_IO_Running: Yes
-- Slave_SQL_Running: Yes
-- Seconds_Behind_Master: 0
在 Master 端追加 Slave 配置,在 Slave 端追加 Master 配置,server-id 必須不同。關鍵防衝突:
auto_increment_offset / auto_increment_increment 錯開自增 ID。Seconds_Behind_Master、Slave_*_Running、Binlog 延遲。| 現象 | 排查 | 處理 |
|---|---|---|
| IO_Running=No | 網絡/防火牆/賬號/密碼/主機名解析 | telnet 3306、檢查 GRANT、hosts 文件 |
| SQL_Running=No | SQL 執行錯誤 (主鍵衝突、表結構差異) | SHOW SLAVE STATUS\G 看 Last_Error,手動修復後 START SLAVE |
| Seconds_Behind_Master 巨大 | Slave 機器性能弱/大事務/長鎖表/網絡延遲 | 優化 SQL、升級硬體、並行複製 (5.6+) |
| Binlog 丟失 | Master expire_logs_days 過短/手動 PURGE | 重新同步基線、調大 expire_logs_days |