备注:君子性非议也,善假于物也。 温故而知新,可以为师矣。
使用MySQL+keepalived是一种非常好的解决方案,在MySQL-HA环境中,MySQL互为主从关系,这样就保证了两台 MySQL数据的一致性,然后用keepalived实现虚拟IP,通过keepalived自带的服务监控功能来实现MySQL故障时自动切换。
实验环境中用两台主机搭建了一个mysql主从复制的环境,两台机器分别安装了keepalived,用一个虚IP实现mysql服务器的主备自动切换功能.
模拟环境:
VIP:192.168.1.197 :虚拟IP地址
Master:192.168.1.198 :主数据库IP地址
Slave:192.168.1.199 :从数据库IP地址
备注:MySQL的主从同步配置不在此文档中说明(前提:主从同步已完成)
安装步骤:
1、keepalived的安装
Yum install -y keepalived
Chkconfig keepalived on
2、keepalived.conf文件的配置
Master:keepalived.conf
vi /etc/keepalived/keepalived.conf
! Configuration File for keepalived
global_defs {
notification_email {
2729705372@qq.com
}
notification_email_from2729705372@qq.com
smtp_connect_timeout 3
smtp_server smtp.xishiqu.com
router_id MySQL-ha
}
vrrp_script check_run { #声明vrrp_script 的函数check_run
script "/root/keepalived_check_mysql.sh" #监控MySQL的脚本
interval 5
}
vrrp_sync_group VG1 {
group {
VI_1
}
}
vrrp_instance VI_1 {
state MASTER #指定主服务器节点为主节点,备用节点上设置需一致
interface eth0 #指定虚拟IP的网络接口
virtual_router_id 88 #VRRP组名,两个节点的设置必须一样,以指明各个节点属于同一VRRP组
priority 100 #主节点的优先级(1-254之间),备用节点必须比主节点优先级低。
advert_int 1 #组播信息发送间隔,两个节点设置必须一样
nopreempt
authentication { #设置验证信息,两个节点必须一致
auth_type PASS
auth_pass 1111
}
track_script { #调用函数代码块
check_run
}
virtual_ipaddress { #虚拟IP(对外提供MySQL服务的IP地址)
192.168.1.197 #不能和网内其他IP地址冲突
}
}
Slave:keepalived.conf
! Configuration File for keepalived
global_defs {
notification_email {
2729705372@qq.com
}
notification_email_from2729705372@qq.com
smtp_connect_timeout 3
smtp_server smtp.xishiqu.cn
router_id MySQL-ha
}
vrrp_script check_run {
script "/root/keepalived_check_mysql.sh"
interval 5
}
vrrp_sync_group VG1 {
group {
VI_1
}
}
vrrp_instance VI_1 {
state MASTER
interface eth1 #本地网口 按实际情况配置
virtual_router_id 88
priority 99
advert_int 1
nopreempt
authentication {
auth_type PASS
auth_pass 1111
}
track_script {
check_run
}
virtual_ipaddress {
192.168.1.197
}
}
3、mysql状态检测脚本
在目录root下创建脚本keepalived_check_mysql.sh:
vim /root/keepalived_check_mysql.sh
#!/bin/bash
MYSQL=/usr/local/mysql/bin/mysql
MYSQL_HOST=localhost
MYSQL_USER=root
MYSQL_PASSWORD=123456
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
pkill keepalived
exit 1
fi
sleep 1
Done
Chmod 755 /root/keepalived_check_mysql.sh
4、两台服务器同时启动mysql和keepalived
Service keepalived restart
Service mysqld restart
5、功能验证
#Ip a :通过查看虚拟IP,验证keepalived服务是否启动
#tcpdump vrrp :查看vrrp通读记录,进行测试
由keepalived的配置文件可知,mysql关闭的话,将会执行keepalived_check_mysql.sh这一脚本。这个脚本在执行的时候,会判断mysql的状态,如果mysql关闭了,将会关闭keepalived进程,将mysqld的服务切换到从数据库。而后主数据修复,需手动切换到主数据库,再重启keepalived服务。Keepalived和nagios配合使用才能提供更好的服务。