實現一主一從異步複製,讀寫分離降低主庫壓力,從庫承擔備份與分析查詢,故障時可手動/自動切換提升可用性。
| 角色 | IP | Server ID | MySQL 版本 |
|---|---|---|---|
| Master | 192.168.4.191 | 1 | 5.7.x |
| Slave | 192.168.4.192 | 2 | 5.7.x |
# /etc/my.cnf [mysqld] 區塊
server-id = 1
log-bin = mysql-bin
binlog-format = ROW # 推薦 ROW 格式,數據一致性最高
binlog-do-db = business_db # 只同步業務庫
binlog-ignore-db = mysql,sys,performance_schema,information_schema
sync_binlog = 1 # 每次提交刷盤,最安全
innodb_flush_log_at_trx_commit = 1
gtid_mode = ON # 5.6+ 推薦啟用 GTID
enforce_gtid_consistency = ON
log-slave-updates = ON # 鏈式複製必備
systemctl restart mysqld
CREATE USER 'repl'@'192.168.4.%' IDENTIFIED BY 'StrongPass#2024';
GRANT REPLICATION SLAVE ON *.* TO 'repl'@'192.168.4.%';
FLUSH PRIVILEGES;
FLUSH TABLES WITH READ LOCK;
SHOW MASTER STATUS;
+------------------+----------+--------------+------------------+
| File | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+----------+--------------+------------------+
| mysql-bin.000007 | 528 | business_db | mysql,sys,... |
+------------------+----------+--------------+------------------+
UNLOCK TABLES;
# Master 打包數據目錄
tar czf /tmp/master_data.tar.gz /var/lib/mysql --exclude=*.pid --exclude=*.err --exclude=auto.cnf
# 傳輸至 Slave
scp /tmp/master_data.tar.gz 192.168.4.192:/tmp/
# Slave 解壓覆蓋(需先停止 mysqld)
systemctl stop mysqld
rm -rf /var/lib/mysql/*
tar xzf /tmp/master_data.tar.gz -C /
chown -R mysql:mysql /var/lib/mysql
systemctl start mysqld
# /etc/my.cnf [mysqld]
server-id = 2
log-bin = mysql-bin
relay-log = relay-bin
read-only = 1 # 防止誤寫入
gtid_mode = ON
enforce_gtid_consistency = ON
log-slave-updates = ON
replicate-do-db = business_db
replicate-ignore-db = mysql,sys,performance_schema,information_schema
systemctl restart mysqld
CHANGE MASTER TO
MASTER_HOST = '192.168.4.191',
MASTER_USER = 'repl',
MASTER_PASSWORD = 'StrongPass#2024',
MASTER_AUTO_POSITION = 1; # GTID 自動定位
START SLAVE;
SHOW SLAVE STATUS\G
# 關鍵指標
Slave_IO_Running: Yes
Slave_SQL_Running: Yes
Seconds_Behind_Master: 0
Last_IO_Error:
Last_SQL_Error:
Master_Server_Id: 1
Retrieved_Gtid_Set: xxxx
Executed_Gtid_Set: xxxx
| 現象 | 原因 | 處理 |
|---|---|---|
| IO_Running=Connecting | 網絡不通/賬號密碼錯/防火牆 | telnet master 3306;檢查 grants;iptables |
| SQL_Running=No | 數據衝突/缺表/外鍵失敗 | 查 Last_SQL_Error;跳過錯誤 SET GLOBAL sql_slave_skip_counter=1; START SLAVE;(謹慎) |
| Seconds_Behind_Master 大 | 從庫硬件弱/大事務/長查詢阻塞 | 優化從庫索引;並行複製 slave_parallel_workers=4 |
| GTID 不一致 | 手動寫入從庫/多源複製 | 重新同步或 RESET MASTER 後重建 |
生產環境建議部署 Orchestrator 管理拓撲,配合 VIP 或 ProxySQL 實現秒級故障轉移。核心原理:監控主庫心跳 → 選舉最新從庫 → 提升為新主 → 重導其他從庫 → 更新路由。
xtrabackup --slave-info 物理備份,不影響主庫主從複製是 MySQL 高可用基石,配置規範化、監控自動化、演練常態化,才能在故障時從容應對。