MySQL主從切換手冊
Master-Slave架構
正常切換
- 檢查slave同步狀態
在開始切換之前先對主庫進行鎖表:
flush tables with read lock
(在執行完成后生產環境必須等待所有語句執行完成)
在flush tables with read lock成功獲得鎖之前,必須等待所有語句執行完成(包括SELECT)。所以如果有個慢查詢在執行,或者一個打開的事務,或者其他進程拿着表鎖,flush tables with read lock就會被阻塞,直到所有的鎖被釋放。請看下面的例子:
mysql> show processlist;
+----+------+-----------+------+------------+------+-------------------+----------------------------------------------------------------------+
| Id | User | Host | db | Command | Time | State | Info |
+----+------+-----------+------+------------+------+-------------------+----------------------------------------------------------------------+
| 4 | root | localhost | test | Query | 80 | Sending data | select count(*) from t t1 join t t2 join t t3 join t t4 where t1.b=0 |
| 5 | root | localhost | test | Query | 62 | Flushing tables | flush tables with read lock |
| 6 | root | localhost | test | Field List | 35 | Waiting for table | |
| 7 | root | localhost | test | Query | 0 | NULL | show processlist |
+----+------+-----------+------+------------+------+-------------------+----------------------------------------------------------------------+
4 rows in set (0.00 sec)
flush data
切換完成后可以釋放鎖
unlock tables
1)在master執行:show processlist;
顯示Master has sent all binlog to slave; waiting for binlog to be updated
2)在slave執行:show processlist;
顯示Slave has read all relay log; waiting for the slave I/O thread to update it
mysql> show slave status \G;
檢查IO及SQL線程是否正常,如果為NO表明同步不一致,需要重新將slave同步保持主從數據一致。
3)停止slave io線程
在slave執行:mysql> STOP SLAVE IO_THREAD
mysql> SHOW PROCESSLIST;
確保狀態為:has read all relay log
以上都執行完成后可以把slave提升為master:
4)提升slave為master
Stop slave;
Reset master;
Reset slave all; 在5.6.3版本之后
Reset slave; 在5.6.3版本之前
查看slave是否只讀模式:show variables like 'read_only';
只讀模式需要修改my.cnf文件,注釋read-only=1並重啟mysql服務。
或者不重啟使用命令關閉只讀,但下次重啟后失效:set
global
read_only=off;
mysql> show master status \G;
備注:reset slave all 命令會刪除從庫的 replication 參數,之后 show slave status\G 的信息返回為空。
5)將原來master變為slave
在新的master上創建同步用戶:
grant replication slave on *.* repl@'IP of slave' identified by 'replpwd';
在新的slave上重置binlog:
Reset master;
change master to master_host='192.168.0.104', //Master 服務器Ip
master_port=3306,
master_user='repl',
master_password=’replpwd’,
master_log_file='master-bin.000001',//Master服務器產生的日志
master_log_pos=?;//master binlog pos
以上最后兩步可以在master執行:show master status
啟動slave:start slave; 並查看slave狀態:show slave status\G;
異常切換
主機故障或者宕機:
1) 在salve執行:
stop slave;
reset master;
查看是否只讀模式:show variables like 'read_only';
只讀模式需要修改my.cnf文件,注釋read-only=1並重啟mysql服務。
或者不重啟使用命令關閉只讀,但下次重啟后失效:set
global
read_only=off;
查看show slave status \G;
查看show master status \G;
將從庫IP地址改為主庫IP地址,測試應用連接是否正常。
<完>