萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 資料庫 >> MySQL 教學

MHA 實現 MySQL 5.6 主從自動切換安裝配置教程

MHA Manager + Node 部署與驗證全記錄

基於前述 MySQL 5.6 主從環境,本文詳細說明 MHA 0.52 版本的安裝、SSH 互信、Manager 配置、健康檢查全流程,打造生產級 MySQL 高可用集群。

一、MHA 軟體安裝

依賴套件

yum -y install perl-DBD-MySQL perl-Config-Tiny perl-Log-Dispatch perl-Parallel-ForkManager

RPM 安裝(推薦)

wget https://mysql-master-ha.googlecode.com/files/mha4mysql-node-0.52-0.noarch.rpm
wget https://mysql-master-ha.googlecode.com/files/mha4mysql-manager-0.52-0.noarch.rpm
rpm -ivh mha4mysql-node-0.52-0.noarch.rpm
rpm -ivh mha4mysql-manager-0.52-0.noarch.rpm

源碼安裝 Manager(示例安裝於 Slave 節點)

wget https://mysql-master-ha.googlecode.com/files/mha4mysql-manager-0.52.tar.gz
tar zxvf mha4mysql-manager-0.52.tar.gz
cd mha4mysql-manager-0.52
perl Makefile.PL && make && make install

Node 端兩台主機均需安裝 mha4mysql-node。

二、基礎環境配置

  1. SSH 免密互信:Manager 節點分別向 Master/Slave、Master 向 Slave、Slave 向 Master 配置 ssh-keygen -t rsa + ssh-copy-id(過程略)。
  2. MySQL 互訪授權
    # 10.1.1.231 (Master) 執行
    GRANT ALL PRIVILEGES ON *.* TO 'root'@'10.1.1.234' IDENTIFIED BY 'rootpasswd';
    FLUSH PRIVILEGES;
    
    # 10.1.1.234 (Slave) 執行
    GRANT ALL PRIVILEGES ON *.* TO 'root'@'10.1.1.231' IDENTIFIED BY 'rootpasswd';
    FLUSH PRIVILEGES;
    

三、Manager 配置文件 /etc/masterha/app1.cnf

[server default]
manager_workdir=/masterha/app1/
manager_log=/masterha/app1/manager.log
user=root
password=d3n0v0
ssh_user=root
repl_user=jpsync
repl_password=jpsyncpass2014la
ping_interval=1
shutdown_script=""
master_ip_failover_script=""
master_ip_online_change_script=""
report_script=""

[server1]
hostname=10.1.1.231
port=63306
master_binlog_dir="/state/partition1/mysql/data"
candidate_master=1

[server2]
hostname=10.1.1.234
port=63306
master_binlog_dir="/state/partition1/mysql/data"
candidate_master=1

關鍵參數:candidate_master=1 標記該節點具備提升為 Master 資格;master_binlog_dir 需與實際 Binlog 目錄一致。

四、配置驗證三部曲

1. SSH 連線測試

masterha_check_ssh --conf=/etc/masterha/app1.cnf
# 輸出 "All SSH connection tests passed successfully." 即通過

2. Manager 進程狀態

masterha_check_status --conf=/etc/masterha/app1.cnf
# app1 (pid:11444) is running(0:PING_OK), master:10.1.1.231

3. 複制健康度深度檢查

masterha_check_repl --conf=/etc/masterha/app1.cnf

輸出重點解讀:

  • Alive Master:10.1.1.231:3306
  • Alive Slave:10.1.1.234:3306,標記為 Primary candidate for the new Master
  • 警告項:
    • Slave 未設 relay_log_purge=0(建議補上)
    • 未定義 master_ip_failover_script、shutdown_script(生產環境必須實作 VIP 漂移與關機腳本)
  • 結論:MySQL Replication Health is OK,MHA 可正常接管故障切換。

五、生產環境補充建議

  • 實作 master_ip_failover_script 整合 Keepalived/VIP 或云廠商 API 實現 IP 漂移
  • 配置 shutdown_script 確保故障主庫徹底下線(防止腦裂)
  • 啟用 report_script 對接告警系統(郵件/企業微信/釘釘)
  • 定期演練 masterha_master_switch --master_state=alive 計劃性切換驗證流程
copyright © 萬盛學電腦網 all rights reserved