場景與前置條件
- 單機模擬雙實例:MySQL 5.1 (Port 3307) 作為 Master,MySQL 5.2 (Port 3308) 作為 Slave
- 各實例獨立 `basedir`、`datadir`、`my.ini`
- 防火牆放行 3307/3308
實例配置
Master (MySQL 5.1) - my.ini
[client]
port=3307
[mysqld]
port=3307
basedir="E:/MySQL5.1/"
datadir="E:/MySQL5.1/Data/"
server-id=1
log-bin=E:\MySQL5.1\Data\mysql-bin.log
binlog-do-db=cnb
binlog_format=ROW
Slave (MySQL 5.2) - my.ini
[client]
port=3308
[mysqld]
port=3308
basedir="E:/MySQL5.2/"
datadir="E:/MySQL5.2/Data/"
server-id=2
relay-log=E:\MySQL5.2\Data\relay-bin.log
read_only=ON
replicate-do-db=cnb
建立複制賬號(在 Master 執行)
mysql -uroot -p -P3307
GRANT REPLICATION SLAVE ON *.* TO 'slave'@'localhost' IDENTIFIED BY '123456';
FLUSH PRIVILEGES;
獲取 Master 同步位點
SHOW MASTER STATUS;
+------------------+----------+--------------+------------------+
| File | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+----------+--------------+------------------+
| mysql-bin.000001 | 154 | cnb | |
+------------------+----------+--------------+------------------+
配置 Slave 同步
mysql -uroot -p -P3308
CHANGE MASTER TO
MASTER_HOST='127.0.0.1',
MASTER_PORT=3307,
MASTER_USER='slave',
MASTER_PASSWORD='123456',
MASTER_LOG_FILE='mysql-bin.000001',
MASTER_LOG_POS=154;
START SLAVE;
驗證同步狀態
SHOW SLAVE STATUS \G
*************************** 1. row ***************************
Slave_IO_State: Waiting for master to send event
Master_Host: 127.0.0.1
Master_User: slave
Master_Port: 3307
Slave_IO_Running: Yes
Slave_SQL_Running: Yes
Seconds_Behind_Master: 0
功能測試
- Master 建表插入:`USE cnb; CREATE TABLE t(id INT); INSERT INTO t VALUES(1);`
- Slave 查詢:`USE cnb; SELECT * FROM t;` → 能看到資料
- Slave 嘗試寫入:`INSERT INTO t VALUES(2);` → 報錯 `The MySQL server is running with the --read-only option`(預期行為)
Windows 環境特有注意事項
- 路徑使用反斜槓 `\` 或正斜槓 `/` 均可,建議統一用 `/`
- 服務管理:`net start mysql51` / `net stop mysql51` 或 `sc create` 註冊服務
- 多實例建議註冊為不同服務名:`mysqld --install mysql51 --defaults-file=E:\MySQL5.1\my.ini`
- 防火牆規則需分別放行 3307、3308
- 日誌檔案路徑建議放在各自 `datadir` 下,避免權限問題
常見問題排查
| 現象 | 原因 | 解決 |
| IO_Running=Connecting | 端口/防火牆/密碼/主機名 | telnet 測試端口、檢查防火牆、用 IP 代替 localhost |
| SQL_Running=No, Last_Error=1062 | 主鍵衝突 | 檢查 Slave 是否誤寫入、或重新同步 |
| Seconds_Behind_Master=NULL | IO 線程未運行 | 優先解決 IO 問題 |