Master (10.1.123.197) ───binlog dump───► Slave (10.1.123.160)
server-id=1 server-id=2
log-bin=mysql-bin relay-log=slave-relay-bin
binlog_format=mixed read_only=1 (推薦)
sync_binlog=1 sync_relay_log=1
[mysqld]
server-id = 1
log-bin = mysql-bin
log-bin-index = mysql-bin.index
binlog_format = MIXED -- 推薦:兼容 Statement/Row,減少主從不一致
sync_binlog = 1 -- 每次提交刷盤,最強持久化,性能略損
max_allowed_packet = 100M -- 大事務/大字段必調大
-- 僅同步指定庫,忽略系統庫
binlog-do-db = testdb
binlog-ignore-db = mysql
binlog-ignore-db = performance_schema
binlog-ignore-db = information_schema
[mysqldump]
max_allowed_packet = 100M
CREATE USER 'repl'@'%' IDENTIFIED BY 'strong_password';
GRANT REPLICATION SLAVE ON *.* TO 'repl'@'%';
FLUSH PRIVILEGES;
[mysqld]
server-id = 2
log-bin = mysql-bin -- Slave 開啟 binlog 利於鏈式複製/備份
relay-log = slave-relay-bin
relay-log-index = slave-relay-bin.index
read_only = 1 -- 防止誤寫入
-- 5.5 專用同步參數
sync_master_info = 1
sync_relay_log = 1
sync_relay_log_info = 1
CHANGE MASTER TO
MASTER_HOST='10.1.123.197',
MASTER_USER='repl',
MASTER_PASSWORD='strong_password',
MASTER_PORT=3306,
MASTER_LOG_FILE='mysql-bin.000001',
MASTER_LOG_POS=107;
-- Master 端
SHOW MASTER STATUS\G; -- 獲取最新 File, Position
-- Slave 端
STOP SLAVE;
CHANGE MASTER TO
MASTER_LOG_FILE='mysql-bin.000005',
MASTER_LOG_POS=12345;
START SLAVE;
yum -y install ntpdate
ntpdate cn.pool.ntp.org
hwclock -w
-- 主從時間差 > 1s 會導致 Seconds_Behind_Master 不準、基於時間的分區裁剪異常
# Master 熱備份帶 binlog 位置
mysqldump -uroot -pxxx -h127.0.0.1 \
--databases db1 db2 db3 \
--master-data=1 --single-transaction \
> bak.sql
# 新 Slave 導入
mysql -uroot -pxxx < bak.sql
-- bak.sql 末尾自帶 CHANGE MASTER TO ... 語句
# 啟動同步
START SLAVE;
**關鍵參數:** `--master-data=1` 輸出 `CHANGE MASTER` 語句;`--single-transaction` 保證一致性視圖 (InnoDB)。
| 操作 | 命令 |
|---|---|
| 鎖表備份 | FLUSH TABLES WITH READ LOCK; |
| 解鎖 | UNLOCK TABLES; |
| 重置 Master | RESET MASTER; (清空 binlog) |
| 重置 Slave | RESET SLAVE; (清空 relay log, 同步位置) |
| 跳過錯誤 | STOP SLAVE; SET GLOBAL sql_slave_skip_counter=1; START SLAVE; (慎用) |