萬盛學電腦網

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

Keepalived 實現 MySQL 主從故障自動切換:完整配置與腳本詳解

架構選型:為什麼選 Master-Slave 而非雙 Master?

雙 Master 架構雙寫看似高可用,但存在嚴重風險:主庫壓力大時從庫同步延遲(如落後 2000 秒),主庫掛掉後 VIP 漂移到從庫,用戶新寫入的數據在從庫未同步完成前不可見;原主庫恢復後,從庫的 IO/SQL 線程仍在運行,會繼續同步舊數據,導致用戶新數據被覆蓋、造成數據丟失。
因此本方案採用 單向 Master-Slave + Keepalived VIP 漂移,確保任意時刻僅有一個寫入節點,數據一致性有保障。

Keepalived 核心配置 /etc/keepalived/keepalived.conf

global_defs {
    router_id KeepAlive_Mysql
}

vrrp_script check_run {
    script "/root/sh/mysql_check.sh"
    interval 300          # 每 5 分鐘檢查一次
}

vrrp_sync_group VG1 {
    group { VI_1 }
}

vrrp_instance VI_1 {
    state BACKUP           # 兩節點均設 BACKUP,由 priority 決定主備
    interface eth0
    virtual_router_id 51
    priority 100           # 主庫設 100,從庫設 90
    advert_int 1
    nopreempt              # 非搶佔模式,避免主庫恢復後頻繁切換
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    track_script {
        check_run
    }
    notify_master /root/sh/master.sh
    notify_backup /root/sh/backup.sh
    notify_stop /root/sh/stop.sh
    virtual_ipaddress {
        192.168.8.150      # VIP,應用層連結此 IP
    }
}

四大狀態通知腳本詳解

1. 健康檢查腳本 mysql_check.sh

每 5 分鐘執行,連續 5 次檢測失敗則停止 Keepalived 觸發切換。

#!/bin/bash
. /root/.bash_profile

count=1
while true; do
    mysql -e "show status;" > /dev/null 2>&1
    i=$?
    ps aux | grep mysqld | grep -v grep > /dev/null 2>&1
    j=$?
    # MySQL 服務正常且進程存在
    if [ $i -eq 0 ] && [ $j -eq 0 ]; then
        exit 0
    # 連接失敗但進程在(可能是暫時卡頓),不計入失敗次數
    elif [ $i -eq 1 ] && [ $j -eq 0 ]; then
        exit 0
    else
        if [ $count -gt 5 ]; then
            break
        fi
        let count++
        sleep 1
        continue
    fi
done
/etc/init.d/keepalived stop

2. 成為 Master 時執行 master.sh

核心邏輯:等待從庫同步追上(最多 60 秒)→ 停止同步 → 修改業務賬號密碼授權寫入 → 記錄新 Master 的 Binlog 位點。

#!/bin/bash
. /root/.bash_profile

# 獲取當前同步進度
Master_Log_File=$(mysql -e "show slave status\G" | grep -w Master_Log_File | awk -F': ' '{print $2}')
Relay_Master_Log_File=$(mysql -e "show slave status\G" | grep -w Relay_Master_Log_File | awk -F': ' '{print $2}')
Read_Master_Log_Pos=$(mysql -e "show slave status\G" | grep -w Read_Master_Log_Pos | awk -F': ' '{print $2}')
Exec_Master_Log_Pos=$(mysql -e "show slave status\G" | grep -w Exec_Master_Log_Pos | awk -F': ' '{print $2}')

i=1
while true; do
    # Relay 已追上 Master,同步完成
    if [ "$Master_Log_File" = "$Relay_Master_Log_File" ] && [ $Read_Master_Log_Pos -eq $Exec_Master_Log_Pos ]; then
        echo "ok"
        break
    else
        sleep 1
        if [ $i -gt 60 ]; then
            echo "timeout, force stop slave"
            break
        fi
        let i++
    fi
done

mysql -e "stop slave;"
mysql -e "flush logs; GRANT ALL PRIVILEGES ON *.* TO 'admin'@'%' IDENTIFIED BY 'admin'; flush privileges;"
mysql -e "show master status;" > /tmp/master_status_$(date "+%y%m%d-%H%M").txt

3. 降為 Backup 時執行 backup.sh

撤銷寫入權限,將業務賬號密碼改回唯讀密碼。

#!/bin/bash
. /root/.bash_profile
mysql -e "GRANT ALL PRIVILEGES ON *.* TO 'admin'@'%' IDENTIFIED BY '1q2w3e4r'; flush privileges;"

4. Keepalived 停止時執行 stop.sh

確保數據不丟失:修改密碼 → 開啟雙寫安全參數 → 等待無寫入操作(最多 60 秒)。

#!/bin/bash
. /root/.bash_profile
mysql -e "GRANT ALL PRIVILEGES ON *.* TO 'admin'@'%' IDENTIFIED BY '1q2w3e4r'; flush privileges;"
mysql -e "set global innodb_support_xa=1;"
mysql -e "set global sync_binlog=1;"
mysql -e "set global innodb_flush_log_at_trx_commit=1;"

M_File1=$(mysql -e "show master status\G" | awk -F': ' '/File/{print $2}')
M_Position1=$(mysql -e "show master status\G" | awk -F': ' '/Position/{print $2}')
sleep 1
M_File2=$(mysql -e "show master status\G" | awk -F': ' '/File/{print $2}')
M_Position2=$(mysql -e "show master status\G" | awk -F': ' '/Position/{print $2}')

i=1
while true; do
    if [ "$M_File1" = "$M_File2" ] && [ $M_Position1 -eq $M_Position2 ]; then
        echo "ok, no writes pending"
        break
    else
        sleep 1
        if [ $i -gt 60 ]; then break; fi
        let i++
        M_File1=$M_File2; M_Position1=$M_Position2
        M_File2=$(mysql -e "show master status\G" | awk -F': ' '/File/{print $2}')
        M_Position2=$(mysql -e "show master status\G" | awk -F': ' '/Position/{print $2}')
    fi
done

部署檢查清單

  • 兩台伺服器時間同步(ntpdate)。
  • MySQL 主從同步正常運行(Seconds_Behind_Master=0)。
  • 防火牆開放 VRRP 協議(多播 224.0.0.18)及 MySQL 3306 端口。
  • mysql_check.sh、master.sh、backup.sh、stop.sh 均有執行權限(chmod +x)。
  • 測試:手動停止主庫 MySQL,觀察 VIP 是否在 5 分鐘內漂移,應用連線是否自動恢復。

總結

這套方案通過 Keepalived 的健康檢查與狀態機制,結合精心設計的四個通知腳本,實現了 MySQL 主從架構下的「故障自動切換、數據零丟失、權限自動收斂」。關鍵在於 master.sh 中「等待同步追上再停止同步」與 stop.sh 中「等待寫入停滯」兩個等待邏輯,將數據一致性風險降至最低。

copyright © 萬盛學電腦網 all rights reserved