| 角色 | IP | OS | MySQL版本 | Server ID |
|---|---|---|---|---|
| Master | 192.168.1.22 | CentOS 5.2 | 5.1.35 | 1 |
| Slave | 192.168.1.33 | CentOS 5.2 | 5.1.35 | 2 |
mysql> GRANT REPLICATION SLAVE ON *.* TO 'repl'@'192.168.1.33' IDENTIFIED BY 'repl';
mysql> FLUSH PRIVILEGES;
注意:@'192.168.1.33' 限制只允許從庫 IP 連線,提升安全性。
[mysqld]
server-id=1
log-bin=mysql-bin
# 可選:只同步特定庫
# binlog-do-db=test
# binlog-ignore-db=mysql
重啟 MySQL:service mysqld restart
mysql> FLUSH TABLES WITH READ LOCK;
mysql> SHOW MASTER STATUS;
+------------------+----------+--------------+------------------+
| File | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+----------+--------------+------------------+
| mysql-bin.000010 | 106 | | |
+------------------+----------+--------------+------------------+
# 另開終端備份
$ mysqldump -u root -p test > test.sql
mysql> UNLOCK TABLES;
[mysqld]
server-id=2
# 可選:只同步特定庫
# replicate-do-db=test
# replicate-ignore-db=mysql
# master-connect-retry=60
重啟 MySQL。
$ mysql -u root -p test < test.sql
mysql> CHANGE MASTER TO
MASTER_HOST='192.168.1.22',
MASTER_USER='repl',
MASTER_PASSWORD='repl',
MASTER_LOG_FILE='mysql-bin.000010',
MASTER_LOG_POS=106;
mysql> START SLAVE;
mysql> SHOW SLAVE STATUS\G
*************************** 1. row ***************************
Slave_IO_State: Waiting for master to send event
Master_Host: 192.168.1.22
Master_User: repl
Master_Port: 3306
Slave_IO_Running: Yes
Slave_SQL_Running: Yes
Seconds_Behind_Master: 0
...
關鍵指標:Slave_IO_Running 與 Slave_SQL_Running 同時為 Yes 表示同步正常。
-- Master 執行
mysql> USE test;
mysql> CREATE TABLE user(id INT);
-- Slave 驗證
mysql> USE test;
mysql> SHOW TABLES LIKE 'user';
+----------------------+
| Tables_in_test(user) |
+----------------------+
| user |
+----------------------+
The slave I/O thread stops because master and slave have equal MySQL server ids
解決:檢查兩端 my.cnf 的 server-id 必須不同,修改後重啟。
-- Master:鎖表並記錄位置
mysql> FLUSH TABLES WITH READ LOCK;
mysql> SHOW MASTER STATUS; -- 記下 File、Position
-- Slave:等待追上該位置
mysql> SELECT MASTER_POS_WAIT('mysql-bin.000011', 260);
-- Master:解鎖
mysql> UNLOCK TABLES;
STOP SLAVE IO_THREAD;,確認 State: Has read all relay logSTOP SLAVE; RESET MASTER;master.info、relay-log.infosync_binlog=1、innodb_flush_log_at_trx_commit=1 保證不丟資料Seconds_Behind_Master,設置告警閾值