Master High Availability (MHA) 是成熟的 MySQL 主從故障切換工具,支援自動故障轉移與手動主從切換。本文記錄手動切換標準化操作流程(Master 存活狀態下的計劃性切換)。
jpsync/jppasswd,管理用戶:root/rootpass
-- 建立 MHA 所需管理/複寫帳號
GRANT ALL PRIVILEGES ON *.* TO 'root'@'10.1.1.231' IDENTIFIED BY 'rootpass';
GRANT ALL PRIVILEGES ON *.* TO 'root'@'10.1.1.234' IDENTIFIED BY 'rootpass';
GRANT REPLICATION SLAVE ON *.* TO 'jpsync'@'10.1.1.231' IDENTIFIED BY 'jppasswd';
GRANT REPLICATION SLAVE ON *.* TO 'jpsync'@'10.1.1.234' IDENTIFIED BY 'jppasswd';
FLUSH PRIVILEGES;
-- 原 Master 設為只讀,凍結寫入
SET GLOBAL read_only = 1;
SHOW VARIABLES LIKE 'read_only'; -- ON
# 交互模式(確認提示)
masterha_master_switch --master_state=alive \
--conf=/etc/masterha/app1.cnf \
--new_master_host=10.1.1.231 \
--new_master_port=63306
# 非交互模式(自動化腳本用)
masterha_master_switch --master_state=alive \
--conf=/etc/masterha/app1.cnf \
--new_master_host=10.1.1.231 \
--new_master_port=63306 \
--interactive=0
--master_state=alive 表示原 Master 存活,MHA 會協調 Binlog 同步、提升新 Master、重新導向舊 Slave。
mysql> SHOW MASTER STATUS;
+-------------------------+----------+--------------+--------------------------------------+
| File | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+-------------------------+----------+--------------+--------------------------------------+
| mysql-master-bin.000013 | 120 | denovo_ng | mysql,denovo,test,information_schema |
+-------------------------+----------+--------------+--------------------------------------+
CHANGE MASTER TO
MASTER_HOST='10.1.1.231',
MASTER_PORT=63306,
MASTER_USER='jpsync',
MASTER_PASSWORD='jppasswd',
MASTER_LOG_FILE='mysql-master-bin.000013',
MASTER_LOG_POS=120;
START SLAVE;
SHOW SLAVE STATUS\G
-- 關鍵:Slave_IO_Running=Yes, Slave_SQL_Running=Yes
-- 新 Master 查看從庫連線
SHOW SLAVE HOSTS;
+-----------+------+-------+-----------+--------------------------------------+
| Server_id | Host | Port | Master_id | Slave_UUID |
+-----------+------+-------+-----------+--------------------------------------+
| 1052 | | 63306 | 1025 | e25a3e4a-39c0-11e4-80cb-00259086c4b6 |
+-----------+------+-------+-----------+--------------------------------------+
-- 測試寫入同步
INSERT INTO test_slave_002 VALUES(555551111,1,55555,99999,44.11,2222,91919);
-- 新 Slave 查詢
SELECT * FROM test_slave_002 WHERE id=555551111; -- 應可見
[mysqld]
skip_slave_start # 防止重啟後誤啟動 Slave 線程(單向複寫拓撲)
[mysqld]
read_only = 1 # 強制只讀,防誤寫
relay_log_purge = 0 # 保留 Relay Log 便於故障排查
systemctl restart mysql # 兩側重啟
-- Master 狀態
SHOW PROCESSLIST; -- 應見 Binlog Dump 線程
SHOW MASTER STATUS;
-- Slave 狀態
SHOW SLAVE STATUS\G -- IO/SQL Running=Yes, Seconds_Behind_Master=0
SHOW PROCESSLIST; -- 見 System user (IO/SQL 線程)
| 問題 | 原因 | 對策 |
|---|---|---|
| 切換後 Slave_IO_Running=Connecting | 網路不通/帳號密碼錯/防火牆 | telnet master 3306;檢查 GRANT 宿主匹配 |
| Seconds_Behind_Master 增長 | SQL 線程慢/大事務/鎖等待 | SHOW PROCESSLIST 看 SQL 線程 State;優化慢查詢 |
| 重啟後雙 Master | 未加 skip_slave_start,舊 Master 重啟啟動 Slave | 必加 skip_slave_start;或用 GTID 拓撲自動識別 |
| GTID 模式下 CHANGE MASTER 不需 FILE/POS | GTID 自動定位 | 用 MASTER_AUTO_POSITION=1 |