[mysqld] server-id = 1 log-bin = /var/lib/mysql/binlog/mysql-bin binlog-do-db = business_db # 僅同步指定庫 (可多行) # binlog-ignore-db = test # 忽略庫 binlog_format = ROW sync_binlog = 1 innodb_flush_log_at_trx_commit = 1 expire_logs_days = 7 max_binlog_size = 500M
重啟:service mysqld restart
GRANT REPLICATION SLAVE, RELOAD, SUPER ON *.* TO 'repl'@'%' IDENTIFIED BY 'repl_pass_123' WITH GRANT OPTION; FLUSH PRIVILEGES; SHOW MASTER STATUS; -- 記錄 File (如 mysql-bin.000001) 和 Position (如 107)
[mysqld] server-id = 2 relay-log = /var/lib/mysql/relaylog/relay-bin read-only = 1 # 防止誤寫入 # replicate-do-db = business_db # 可選,Master 已過濾通常無需重複 log_slave_updates = 1 # 若 Slave 又是其他 Slave 的 Master
重啟:service mysqld restart
CHANGE MASTER TO MASTER_HOST='192.168.1.100', MASTER_USER='repl', MASTER_PASSWORD='repl_pass_123', MASTER_PORT=3306, MASTER_LOG_FILE='mysql-bin.000001', MASTER_LOG_POS=107, MASTER_CONNECT_RETRY=10; START SLAVE;
SHOW SLAVE STATUS\G -- 關鍵指標 Slave_IO_Running: Yes Slave_SQL_Running: Yes Seconds_Behind_Master: 0 Last_IO_Error: Last_SQL_Error:
Yes 且 Seconds_Behind_Master=0 → **同步正常**。| 現象 | 原因 | 解決 |
|---|---|---|
| Slave_IO_Running=Connecting | 網絡不通/賬號密碼錯/防火牆/MASTER_HOST 錯誤 | 檢查連通性、SHOW GRANTS、Master 日誌 |
| Slave_SQL_Running=No, Last_SQL_Error: Duplicate entry | 主鍵衝突/Slave 獨立寫入/重複執行 | 跳過錯誤: SET GLOBAL sql_slave_skip_counter=1; START SLAVE; 或重新搭建 |
| Seconds_Behind_Master 巨大/增長 | Slave 執行慢/大事務/硬件差/單線程瓶頸 | 優化 Slave 索引/硬件、升級 5.6+ 多線程複製、關閉不必要從庫查詢 |
| Relay Log 損壞/丟失 | 磁碟故障/手動刪除 | STOP SLAVE; RESET SLAVE; 重新 CHANGE MASTER TO ... (需 Master 仍保留 binlog) |
Slave_IO_Running, Slave_SQL_Running, Seconds_Behind_Master > 300 觸發報警。pt-table-checksum (Percona) 檢測主從數據一致性。
3. **備份策略**:從庫做全量備份 (不影響主庫)、binlog 定期歸檔。
4. **故障切換**:MHA / Orchestrator / GTID (5.6+) 自動化主從切換。
5. **版本升級**:先升 Slave、驗證、再升 Master,或藍綠部署。