MySQL 設定 Master-Slave Replication 同步

MySQL 設定 Master-Slave Replication 同步

<iframe id="aswift_2" style="margin: 0px; padding: 0px; border-width: 0px; border-style: initial; font-style: inherit; font-variant: inherit; font-weight: inherit; font-stretch: inherit; font-size: inherit; line-height: inherit; font-family: inherit; vertical-align: baseline; max-width: 100%; left: 0px; position: absolute; top: 0px;" name="aswift_2" frameborder="0" marginwidth="0" marginheight="0" scrolling="no" width="468" height="15"></iframe>

MySQL 的 Master-Slave Replication (同步) 是當 Master 資料庫有變動時, 自動同步到 Slave 資料庫。由於 MariaDB 在 RHEL/CentOS 7 開始已經成為預設資料庫, 而且可以完全取代 MySQL, 所以以下也會以 MariaDB 進行設定, 但同樣方法在 MySQL 一樣可以的。

假設已經有兩台 MySQL 伺服器, 以下兩部份分別是 Master 及 Slave 的設定。

Master
開啟 /etc/my.cnf 進行設定, 在 [mysqld] 區塊改成以下這樣, 其中 bind-address 要改成 Master 的 ip; datadir 是資料目錄:

 

 

修改後儲存檔案, 重新啟動 MySQL:

# service restart mysql

接著用 root 登入 MySQL, 建立一個用作同步的帳號, 以下會建立帳號 replication, 密碼是 password, Slave 的 ip 是 192.168.1.101:

 

 

然後要用 mysqldump 匯出資料庫的 .sql 檔, 要放到 Slave 匯入:

# mysqldump –skip-lock-tables –all-databases –user=root –password –master-data > masterdatabase.sql

Slave 設定

開啟 /etc/my.cnf 修改設定, 加入以下內容到 [mysqld] 區塊:

 

 

修改後儲存檔案, 重新啟動 MySQL:

# service restart mysql

用 root 登入 MySQL, 建立資料庫:

 

 

將在 Master 用 mysqldump 建立的 masterdatabase.sql 匯入:

mysql -u root -p database-name < masterdatabase.sql

匯入資料後, 再次用 root 登入 MySQL, 執行以下 SQL 指令, 以下的 MASTER_HOST 改為 Master 的 ip, 而 MASTER_LOG_FILE 及 MASTER_LOG_POS 是在 Master 上在 MySQL 執行 “SHOW MASTER STATUS;” 的結果:

 

現在 Slave 已經可以同步, 要查詢 Slave 的狀態, 可以登入 MySQL 用以下指令檢查:

猜你喜欢

转载自fireinwind.iteye.com/blog/2296500