使用Keepalived实现MySQL主从复制的自动切换通常涉及配置一个虚拟IP(VIP)作为MySQL服务器对客户端的访问点。Keepalived会监控MySQL主服务器的健康状况,如果主服务器宕机,Keepalived会自动将虚拟IP移至备用服务器,从而实现故障转移。
以下是一个简化的示例配置,假设您已经有两台配置好的MySQL主从服务器(master和slave)和相应的Keepalived。
在master服务器上的Keepalived配置 (/etc/keepalived/keepalived.conf
):
! Configuration File for keepalivedglobal_defs {
router_id MySQL-HA
}vrrp_script check_mysql {
script "/etc/keepalived/check_mysql.sh"
interval 2
weight 2
}vrrp_instance mysql-ha {
state MASTER
interface eth0
virtual_router_id 51
priority 100
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
track_script {
check_mysql
}
virtual_ipaddress {
192.168.1.200/24 dev eth0 label eth0:1
}
}
在slave服务器上的Keepalived配置 (/etc/keepalived/keepalived.conf
):
! Configuration File for keepalivedglobal_defs {
router_id MySQL-HA
}vrrp_script check_mysql {
script "/etc/keepalived/check_mysql.sh"
interval 2
weight 2
}vrrp_instance mysql-ha {
state BACKUP
interface eth0
virtual_router_id 51
priority 90
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
track_script {
check_mysql
}
virtual_ipaddress {
192.168.1.200/24 dev eth0 label eth0:1
}
}
check_mysql.sh
脚本(位于/etc/keepalived/check_mysql.sh
):
bash#!/bin/bash
if ! mysql -u root -p'your_password' -e "show status;" &>/dev/null; then
exit 1
fi
exit 0
确保将your_password
替换为您的MySQL root用户密码,并给check_mysql.sh
脚本执行权限。
配置完成后,启动Keepalived服务,并确保它们随系统启动。当主服务器出现问题时,Keepalived会自动将VIP转移到备用服务器上。