在mysql主從同步的過程當中,可能會由於各類緣由出現主庫與從庫不一樣步的狀況,網上雖然有一些解決辦法,可是有時很難完全解決,重置主從服務器也許不是最快的辦法,但倒是最安全有效的。mysql
下面將本身重置主從同步的步驟總結一下,以備不時之需。nginx
master與slave均使用:centos6.0+mysql 5.1.61 ,假設有db1,db2兩個數據庫須要熱備。web
文中shell與mysql均使用root帳號,在真實環境中,請根據狀況更換。 sql
1.中止slave服務器的主從同步shell
爲了防止主從數據不一樣步,須要先中止slave上的同步服務。數據庫
STOP SLAVE;
2.對master服務器的數據庫加鎖apache
爲了不在備份的時候對數據庫進行更新操做,必須對數據庫加鎖。centos
FLUSH TABLES WITH READ LOCK;
若是是web服務器也能夠關閉apache或nginx服務,效果也是同樣的。安全
3.備份master上的數據服務器
mysqldump -u root -p -databases db1 db2 > bak.sql
4.重置master服務
RESET MASTER;
這個是重置master的核心語法,看一下官方解釋。
RESET MASTER removes all binary log files that are listed in the index file, leaving only a single, empty binary log file with a numeric suffix of .000001, whereas the numbering is not reset by PURGE BINARY LOGS.
RESET MASTER is not intended to be used while any replication slaves are running. The behavior of RESET MASTER when used while slaves are running is undefined (and thus unsupported), whereas PURGE BINARY LOGS may be safely used while replication slaves are running.
大概的意思是RESET MASTER將刪除全部的二進制日誌,建立一個.000001的空日誌。RESET MASTER並不會影響SLAVE服務器上的工做狀態,因此盲目的執行這個命令會致使slave找不到master的binlog,形成同步失敗。
可是咱們就是要重置同步,因此必須執行它。
5.對master服務器的數據庫解鎖
UNLOCK TABLES;
若是你中止了apache或nginx,請開啓它們
6.將master上的備份文件拷貝到slave服務器上
大可沒必要用WinScp先下載到本地再上傳到slave上,能夠直接使用scp命令在服務器間拷貝,速度更快。
scp -r root@XXX.XXX.XXX.XXX:/root/bak.sql ./
7.刪除slave服務器上的舊數據
刪除前,請先確認該備份的是否都備份了。
DROP DATABASE db1; DROP DATABASE db2;
8.導入數據
SOURCE /root/bak.sql;
9.重置slave服務
RESET SLAVE;
仍是看一下官方解釋
RESET SLAVE makes the slave forget its replication position in the master's binary log. This statement is meant to be used for a clean start: It deletes the master.info and relay-log.info files, all the relay log files, and starts a new relay log file. To use RESET SLAVE, the slave replication threads must be stopped (use STOP SLAVE if necessary).
大概意思是,RESET SLAVE將清除slave上的同步位置,刪除全部舊的同步日誌,使用新的日誌從新開始,這正是咱們想要的。須要注意的是,必須先中止slave服務(STOP SLAVE),咱們已經在第一步中止了它。
10.開啓slave服務
START SLAVE;
大功告成,SHOW SLAVE STATUS\G 檢查同步狀態,一切正常。