通过keepalived实现 MySQL VIP 自动切换
首先配置keepalived。链接如下:
http://blog.itpub.net/28939273/viewspace-1808369/
主服务器keepalived的配置文件内容如下:
[root@yoon keepalived]# cat keepalived.conf
vrrp_script check_mysql_port {
script "/etc/keepalived/keepalived_check_mysql.sh"
interval 1
weight -10
}
global_defs {
router_id MYSQL_YOON
}
vrrp_instance mysql_yoon_master {
state MASTER
interface eth0
virtual_router_id 245
priority 100
advert_int 1
authentication {
auth_type PASS
auth_pass mysql_yoon
}
virtual_ipaddress {
172.16.232.245
}
track_script {
check_mysql_port
}
}
备用服务器keepalived配置文件内容:
[root@back keepalived]# cat keepalived.conf
vrrp_script check_mysql_port {
script "/etc/keepalived/keepalived_check_mysql.sh"
interval 1
weight -10
}
global_defs {
router_id MYSQL_YOON
}
vrrp_instance mysql_yoon_master {
state MASTER
interface eth0
virtual_router_id 245
priority 90
advert_int 1
authentication {
auth_type PASS
auth_pass mysql_yoon
}
virtual_ipaddress {
172.16.232.245
}
track_script {
check_mysql_port
}
}
在/etc/keepalived/下创建keepalived_check_mysql.sh
[root@yoon keepalived]# vi keepalived_check_mysql.sh
#!/bin/bash
MYSQL=/export/servers/mysql/bin/mysql
MYSQL_HOST=127.0.0.1 #如何在执行过程中,keepalived进程莫名自动关闭的话,尝试将127.0.0.1改成localhost,我是由localhsot改成了127.0.0.1才可以,一定要注意
MYSQL_USER=root
MYSQL_PASSWORD=yoon
CHECK_TIME=3
#mysql is working MYSQL_OK is 1 , mysql down MYSQL_OK is 0
MYSQL_OK=1
function check_mysql_helth (){
$MYSQL -h $MYSQL_HOST -u $MYSQL_USER -p${MYSQL_PASSWORD} -e "show status;" >/dev/null 2>&1
if [ $? = 0 ] ;then
MYSQL_OK=1
else
MYSQL_OK=0
fi
return $MYSQL_OK
}
while [ $CHECK_TIME -ne 0 ]
do
let "CHECK_TIME -= 1"
check_mysql_helth
if [ $MYSQL_OK = 1 ] ; then
CHECK_TIME=0
exit 0
fi
if [ $MYSQL_OK -eq 0 ] && [ $CHECK_TIME -eq 0 ]
then
/etc/init.d/keepalived stop
exit 1
fi
sleep 1
done
并在备用服务器上也创建同样的脚本