首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 數據庫知識 >  >> MySQL 資料庫 >> MySQL 綜合教學

MySQL 主從同步完整部署指南:CentOS 5.2 + MySQL 5.1.35 實戰詳解

     編輯:MySQL 綜合教學

環境規格

角色OSMySQLIP
MasterCentOS 5.25.1.35 (源碼編譯)192.168.1.22
SlaveCentOS 5.25.1.35 (源碼編譯)192.168.1.33

一、Master 端配置

1.1 建立複寫帳號

mysql> GRANT REPLICATION SLAVE ON *.* TO 'repl'@'192.168.1.33' IDENTIFIED BY 'repl_pass';
注意:宿主應為 Slave IP(192.168.1.33),原文誤寫為 Master IP。

1.2 編輯 /etc/my.cnf

[mysqld]
server-id = 1
log-bin = mysql-bin
# 註釋掉預設的 server-id=1(若有)

1.3 啟動 MySQL

mysqld_safe --user=mysql &

1.4 加全域讀鎖並記錄 Binlog 位點


mysql> FLUSH TABLES WITH READ LOCK;
mysql> SHOW MASTER STATUS;
+------------------+----------+--------------+------------------+
| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+----------+--------------+------------------+
| mysql-bin.000001 | 106      |              |                  |
+------------------+----------+--------------+------------------+

1.5 備份同步資料庫並解鎖


mysqldump test > test.sql
mysql> UNLOCK TABLES;

二、Slave 端配置

2.1 編輯 /etc/my.cnf


[mysqld]
server-id = 2
# 註釋掉預設 server-id=1

2.2 啟動 Slave MySQL


mysqld_safe --user=mysql &

2.3 配置複寫連線參數


mysql> CHANGE MASTER TO
    -> MASTER_HOST='192.168.1.22',
    -> MASTER_USER='repl',
    -> MASTER_PASSWORD='repl_pass',
    -> MASTER_LOG_FILE='mysql-bin.000001',
    -> MASTER_LOG_POS=106;

2.4 啟動複寫執行緒


mysql> START SLAVE;

三、驗證與監控

3.1 檢查進程狀態


mysql> SHOW PROCESSLIST\G
...
Id: 2
User: system user
State: Has read all relay log; waiting for the slave I/O thread to update it
Info: NULL
出現 system user 且 State 顯示等待 I/O 執行緒更新,表示 Slave 已連接 Master 並開始接收 Relay Log。

3.2 核心狀態檢查


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
Master_Log_File: mysql-bin.000001
Read_Master_Log_Pos: 106
Relay_Log_File: centos-relay-bin.000002
Relay_Log_Pos: 529
Slave_IO_Running: Yes
Slave_SQL_Running: Yes
Seconds_Behind_Master: 0
...
成功標誌:Slave_IO_Running: Yes 且 Slave_SQL_Running: Yes 同時為 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              |
+-------------------+

表結構同步成功,主從複寫部署完成。

關鍵避坑提醒

  • GRANT 宿主必須是 Slave IP,非 Master IP
  • server-id 主從必須不同,且非 0
  • Master 必須開啟 log-bin
  • Slave 啟動前需導入 Master 完整備份(含結構與資料)
  • 防火牆需開放 3306 埠雙向通訊
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved