MySQL高可用性之Keepalived+MySQL(双主热备)
MySQL双主复制,即互为Master-Slave(只有一个Master提供写操作),可以实现数据库服务器的热备,但是一个Master宕机后不能实现动态切换。而Keepalived通过虚拟IP,实现了双主对外的统一接口以及自动检查、失败切换机制。联合使用,可以实现MySQL数据库的高可用方案。
环境描述:
OS:CentOS6.5_X64
MASTER:192.168.196.133
BACKUP:192.168.196.134
VIP:192.168.196.135
操作系统时间一致更改:OS:CentOS6.5_X64
MASTER:192.168.196.133
BACKUP:192.168.196.134
VIP:192.168.196.135
# date -s "20170707 01:51:42"
# hwclock --systohc
1按照之前的文章,搭建双主备机
2安装keepalived
[root@backup ~]# yum install -y pcre-devel openssl-devel popt-devel #安装依赖包
[root@master ~]# wget http://www.keepalived.org/software/keepalived-1.2.7.tar.gz
[root@master ~]# tar zxvf keepalived-1.2.7.tar.gz
[root@master ~]# cd keepalived-1.2.7
[root@master ~]#./configure --prefix=/usr/local/keepalived
[root@master ~]#make && make install
3将keepalived配置成系统服务
[root@master ~]# cp /usr/local/keepalived/etc/rc.d/init.d/keepalived /etc/init.d/
[root@master ~]# cp /usr/local/keepalived/etc/sysconfig/keepalived /etc/sysconfig/
[root@master ~]# mkdir /etc/keepalived/
[root@master ~]# cp /usr/local/keepalived/etc/keepalived/keepalived.conf /etc/keepalived/
[root@master ~]# cp /usr/local/keepalived/sbin/keepalived /usr/sbin/
[root@master ~]# vi /etc/keepalived/keepalived.conf
x
1
! Configuration File for keepalived
2
3
global_defs {
4
notification_email {
5
acassen@firewall.loc
6
failover@firewall.loc
7
sysadmin@firewall.loc
8
}
9
notification_email_from Alexandre.Cassen@firewall.loc
10
smtp_server 192.168.200.1
11
smtp_connect_timeout 30
12
router_id MYSQL_HA #标识,双主相同
13
}
14
15
vrrp_instance VI_1 {
16
state BACKUP #两台都设置BACKUP
17
interface eth1
18
virtual_router_id 51 #主备相同
19
priority 100 #优先级,backup设置90
20
advert_int 1
21
nopreempt #不主动抢占资源,只在master这台优先级高的设置,backup不设置
22
authentication {
23
auth_type PASS
24
auth_pass 1111
25
}
26
virtual_ipaddress {
27
192.168.196.135
28
}
29
}
30
31
virtual_server 192.168.196.135 3306 {
32
delay_loop 2
33
#lb_algo rr #LVS算法,用不到,我们就关闭了
34
#lb_kind NAT #LVS模式,如果不关闭,备用服务器不能通过VIP连接主MySQL
35
nat_mask 255.255.255.0
36
persistence_timeout 50
37
protocol TCP
38
39
real_server 192.168.196.133 3306 { #检测本地mysql,backup也要写检测本地mysql
40
weight 3
41
notify_down /usr/local/keepalived/mysql.sh #当mysq服down时,执行此脚本,杀死keepalived实现切换
42
TCP_CHECK {
43
connect_timeout 3 #连接超时
44
nb_get_retry 3 #重试次数
45
delay_before_retry 3 #重试间隔时间
46
}
47
}
48
}
[root@master ~]# vi /usr/local/keepalived/mysql.sh
#!/bin/bash
pkill keepalived
[root@master ~]# chmod +x /usr/local/keepalived/mysql.sh [root@master ~]# /etc/init.d/keepalived start
#backup服务器只修改priority为90、nopreempt不设置、real_server设置本地IP。
5授权两台Mysql服务器允许root远程登录,用于在其他服务器登陆测试!
6、测试高可用性
1、通过Mysql客户端通过VIP连接,看是否连接成功。
2、停止master这台mysql服务,是否能正常切换过去,可通过ip addr命令来查看VIP在哪台服务器上。
mysql>grant all privileges on *.* to 'root'@'%' identified by 'root';
mysql>flush privileges
1、通过Mysql客户端通过VIP连接,看是否连接成功。
2、停止master这台mysql服务,是否能正常切换过去,可通过ip addr命令来查看VIP在哪台服务器上。
3、可通过查看/var/log/messges日志,看出主备切换过程
4、master服务器故障恢复后,是否主动抢占资源,成为活动服务器。
4、master服务器故障恢复后,是否主动抢占资源,成为活动服务器。
满载一船星辉,在星辉斑斓里放歌