MySQL 3.23.15+ 引入複制功能。核心流程:
master.info雙線程設計(I/O + SQL)解耦網絡傳輸與重放執行,大幅降低延遲。
| 角色 | IP | 端口 | OS | MySQL |
|---|---|---|---|---|
| Master | 192.168.1.100 | 3306 | Win7 | 5.5.20 |
| Slave | 192.168.1.102 | 3306 | Win8 | 5.5.20 |
my.ini 啟用 log-bin、server-id=1、binlog-do-db=testGRANT REPLICATION SLAVE ON *.* TO 'repl'@'%' IDENTIFIED BY '123';mysqldump 導出 Master 數據,source 導入 Slavemy.ini 設置 server-id=2(不要在 [mysql] 區塊配置 binlog)CHANGE MASTER TO ... 指定 MASTER_LOG_FILE/MASTER_LOG_POSSTART SLAVE,驗證 Slave_IO_Running=Yes, Slave_SQL_Running=Yesbinlog。000004 → 應為 binlog.000004log_bin 寫在 [mysql] 而非 [mysqld]repl@'%' 允許遠程,flush privileges| 參數 | 作用 | 建議 |
|---|---|---|
log-slave-updates | Slave 更新寫入自身 Binlog | 級聯複制/雙主必開 |
master-connect-retry=60 | I/O 線程重連間隔(秒) | 默認 60 通常足夠 |
read-only=1 | 限制非超級用戶寫入 Slave | 生產 Slave 強烈建議開啟 |
slave-skip-errors=1007,1051,1062 | 自動跳過指定錯誤碼 | 僅限查詢分流 Slave,備份庫禁用 |
SHOW PROCESSLIST\G
-- 關注 Slave SQL 線程 Time 值
Id: 6 Time: 2769 State: Slave has read all relay log...
-- 表示 Slave 執行進度落後 Master 約 2769 秒
結合 Seconds_Behind_Master(SHOW SLAVE STATUS)綜合判斷。
SHOW SLAVE STATUS\G 確認雙線程 YesLast_IO_Error、Last_SQL_ErrorSeconds_Behind_Master 趨勢pt-table-checksum)| 故障 | 原因 | 處理 |
|---|---|---|
| log event entry exceeded max_allowed_packet | 大 Blob/長文本超過網絡傳輸限制 | 主從同步增大 max_allowed_packet=16M |
| 多主 auto_increment 衝突 | 多寫入節點產生相同自增值 | 設置 auto_increment_increment/auto_increment_offset 錯開 |
| Slave_IO_Running: No, Last_IO_Error 2013 | 網絡中斷/防火牆/賬號權限 | 檢查連通性、GRANT ... @'%'、防火牆 3306 |
| 主從數據不一致 | 直接在 Slave 寫入、跳過錯誤、Binlog 格式問題 | pt-table-sync 修復、重做 Slave |
# 1. 確保 Slave 已應用所有 Relay Log
STOP SLAVE IO_THREAD;
SHOW PROCESSLIST; -- 等待 State: "Slave has read all relay log"
# 2. 停止 Slave,提升為 Master
STOP SLAVE;
RESET MASTER; -- 需開啟 log_bin,否則報錯
# 3. 新 Master 創建複制賬號
GRANT REPLICATION SLAVE ON *.* TO 'repl'@'%' IDENTIFIED BY '123';
SHOW MASTER STATUS; -- 記錄 File/Position
# 4. 原 Master 配置為新 Slave
CHANGE MASTER TO
MASTER_HOST='新Master IP',
MASTER_USER='repl',
MASTER_PASSWORD='123',
MASTER_LOG_FILE='binlog.000005',
MASTER_LOG_POS=107;
START SLAVE;
# 5. 驗證雙向同步
-- 新 Master 建表插數據
-- 原 Master (現 Slave) 查詢驗證
SHOW VARIABLES LIKE 'server_id';
SET GLOBAL server_id = 新唯一值;
-- 重啟後生效,或動態生效視版本而定
rpl_semi_sync_master=ON 關鍵業務零數據丟失