可以看到,VIP已经添加到了server1上,接下来我们在server2安装启动keepalived,启动,所有步骤都一样,只不过server2的keepalived作为备机,并不会持有VIP。
我们在server1上执行
/etc/init.d/keepalived stop
执行以后在ip addr看,VIP现在已经是server2持有了。所以最最基本的功能是已经完成了,但是离我们双主自动切换还是有很大的差距的,下面我们继续去对keepalived的文件进行改造,直到达到我们满意为止:
下面我们修改配置文件,达到我们需要的目的(下面以server2的kp文件为例,server1的和server2一样,只要替换掉相应IP为34就可以了):
vrrp_script checkmysql { script "/etc/keepalived/checkmysql.sh" interval 10 #监控脚本,每十秒运行一次 } vrrp_instance VI_20 { state BACKUP #状态只有MASTER和BACKUP两种,并且要大写,MASTER为工作状态,BACKUP是备用状态 nopreempt #非抢占模式 interface eth0 virtual_router_id 20 priority 100 #权重,同一个vrrp_instance的MASTER优先级必须比BACKUP高。我们使用非抢占模式,设置相同即可 advert_int 5 #MASTER 与BACKUP 负载均衡器之间同步检查的时间间隔,单位为秒 authentication { auth_type PASS #验证authentication。包含验证类型和验证密码。类型主要有PASS、AH 两种,通常使用的类型为PASS auth_pass 1111 } track_script { #执行定义的监控脚本 checkmysql } virtual_ipaddress { 172.16.16.20/24 } }
看一下checkmysql.sh这个脚本:
#!/bin/sh
#isok=$(sed -n '2p' /etc/keepalived/result.txt)
isok=$(/usr/local/mysql/bin/mysql -uroot -p123456 -e 'select 1' |sed -n '2p')
function error_query(){
service keepalived stop
echo "172.16.16.34 mysql down, keepalived 切换" | mail -s "34MySQL+keepalived通知" ma.xiangqian@sf-express.com
}
echo "$isok"
if [ "$isok" != "1" ]
then
#echo 'diaoyong error'
error_query
fi
现在我们执行以下语句,从新load以下keepalived的配置文件:
/etc/init.d/keepalived reload server1和server2都要执行重新load一下新的配置文件,下面我们测试一下当server1 MySQL DOWN掉的话会发生什么: server1:shutdown MySQL server1和server2:tail -f /var/log/messages
server1信息:
May 15 15:35:34 localhost Keepalived_healthcheckers[22987]: TCP connection to [172.16.16.34]:3306 failed !!! May 15 15:35:34 localhost Keepalived_healthcheckers[22987]: Removing service [172.16.16.34]:3306 from VS [172.16.16.20]:3306 May 15 15:35:34 localhost Keepalived_healthcheckers[22987]: IPVS : Virtual service [172.16.16.20]:3306 illegal timeout. May 15 15:35:34 localhost Keepalived_healthcheckers[22987]: Executing [/etc/keepalived/shutdown.sh #检测到服务down后执行的脚本] for service [172.16.16.34]:3306 in VS [172.16.16.20]:3306 May 15 15:35:34 localhost Keepalived_healthcheckers[22987]: Lost quorum 1-0=1 > 0 for VS [172.16.16.20]:3306 May 15 15:36:04 localhost Keepalived_vrrp[22988]: VRRP_Script(checkmysql) failed May 15 15:36:06 localhost Keepalived_vrrp[22988]: VRRP_Instance(VI_20) Entering FAULT STATE May 15 15:36:06 localhost Keepalived_vrrp[22988]: VRRP_Instance(VI_20) removing protocol VIPs. May 15 15:36:06 localhost Keepalived_vrrp[22988]: VRRP_Instance(VI_20) Now in FAULT state May 15 15:36:06 localhost Keepalived_healthcheckers[22987]: Netlink reflector reports IP 172.16.16.20 removed
server2信息: