一、环境
树莓派3B 使用网卡:wlan0 ip:192.168.31.209
树莓派3B 使用网卡:wlan0 ip:192.168.31.194
二、mysql安装和配置
1、每台树莓派上安装一个mysql服务, bind_addr配置成0.0.0.0,绑定树莓派上的所有ip地址
2、两台树莓派上的mysql配置成双M架构,互为主从,网上很多例子,自行查找
三、keepalived安装配置
1、apt-get install keepalived 安装 keepalived 服务
2、树莓派(192.168.31.209) 添加配置文件 /etc/keepalived/keepalived.conf
global_defs{
notification_email{
[email protected]
[email protected]
}
notification_email_from [email protected]
smtp_server 127.0.0.1
stmp_connect_timeout 30
router_id lnmp_node1
}
vrrp_instance lnmp {
state MASTER
interface wlan0
virtual_router_id 100
priority 200
advert_int 5
authentication {
auth_type PASS
auth_pass 123456
}
virtual_ipaddress {
192.168.31.110
}
}
3、树莓派(192.168.31.194) 添加配置文件 /etc/keepalived/keepalived.conf
global_defs{
notification_email{
[email protected]
[email protected]
}
notification_email_from [email protected]
smtp_server 127.0.0.1
stmp_connect_timeout 30
router_id lnmp_node1
}
vrrp_instance lnmp {
state BACKUP
interface wlan0
virtual_router_id 100
priority 150
advert_int 5
authentication {
auth_type PASS
auth_pass 123456
}
virtual_ipaddress {
192.168.31.110
}
}
4、在两台树莓派上分别启动keepalived服务:keepalived -f /etc/keepalived/keepalived.conf 启动的log打印在系统log文件
/var/log/messages里,启动完成之后就生成一个虚拟路由器集群,VIP为配置文件中的192.169.31.110,客户端用这个IP 进行数据库访问和交互
5、可以shutdown一台树莓派,测试配置是否正常,ip是否可以正常切换,用 ip addr命令 可以看到192.169.31.110这个ip在两 台树莓派中切换
三、健康检查脚本
之前的步骤只能解决服务器宕机、掉电导致的问题;无法解决 服务器正常,mysql service异常 这种问题。需要用脚本进行 健康检查,分别在两台树莓排上运行以下脚本,脚本需要配置成开机启动
nohup sh /etc/keepalived/mysqlHealthCheck.sh >/dev/null 2>log &
#!/bin/sh
while :
do
mysql -uroot -proot -e "select version();"
if [ $? -ne 0 ]; then
#echo "mysql error!!!"
service keepalived stop
else
keepalivedcheck=`ps -C keepalived --no-header | wc -l`
if [ $keepalivedcheck -eq 0 ]; then
service keepalived start
else
#echo "keepalived is running"
:
fi
#echo "mysql running!!!"
fi
sleep 5
done
注意:这样进行切换,是不等从数据库把数据同步完就进行切换,可能会出现主从数据不一致的问题。如果要保证主从数据库数据 一致,需要等待从数据库把数据同步完成,需要开发检测数据同步完成的脚本,这是另外一个问题,请自行查阅
测试:service mysql stop 停掉一个mysql 检查客户端数据库访问和交互是否正常