拾遗笔记

mysql 双主 高可用实现方案 keepalived 自动自动切换

目标 实现mysql 高可用性,避免mysql单点故障

Keepalived是一个基于VRRP协议来实现的WEB服务高可用方案,可以利用其来
避免单点故障。一个WEB服务至少会有2台服务器运行 Keepalived,一台为主服
务器(MASTER),一台为备份服务器(BACKUP),但是对外表现为一个虚拟IP,
主服务器会发送特定的消息给备份服务器,当备份服务器收不到这个消息的时
候,即主服务器宕机的时候,备份服务器就会接管虚拟IP,继续提供服务,从
而保证了高可用性

Keepalived的工作原理是VRRP(Virtual Router Redundancy Protocol)虚拟
路由冗余协议。在VRRP中有两组重要的概念:VRRP路由器和虚拟路由器,主控
路由器和备份路由器。

VRRP路由器是指运行VRRP的路由器,是物理实体,虚拟路由器是指VRRP协议创建
的,是逻辑概念。一组VRRP路由器协同工作,共同构成一台虚拟路由器。 Vrrp
中存在着一种选举机制,用以选出提供服务的路由即主控路由,其他的则成了备
份路由。当主控路由失效后,备份路由中会重新选举出一个主控路由,来继续工
作,来保障不间断服务

LVS负载均衡

mysql 双机热备

主从配置见 mysql-slave配置
mysql 的双机热备 基本可以认为是 将主从模式 变成互为主从
虽然互为主从,但仍然采用单点写入,而非同时向两个库写入

惟一需要注意的一点是处理主键自增的时候,需要避免冲突

auto-increment-increment = 2
auto-increment-offset = 1

auto-increment-increment = 2
auto-increment-offset = 2

配置 keepalived

MySQL-master1

vi /etc/keepalived/keepalived.conf
! 开头的为注释

! Configuration File for keepalived
global_defs {
notification_email {
xxx@mail.com
}
notification_email_from xxx@mail.com
smtp_server 127.0.0.1
smtp_connect_timeout 30
router_id MySQL-ha
}

vrrp_instance VI_1 {
state MASTER #标记状态MASTER
interface eth0
virtual_router_id 51
priority 100 #MASTER权重要高于BACKUP
advert_int 1
nopreempt #不抢占,只在优先级高的机器上设置即可
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
192.168.1.200 #VIP虚拟 IP#虚拟IP地址,mysql客户端访问的地址
}
}

virtual_server 192.168.1.200 3306 { #VIP虚拟 IP
delay_loop 2
lb_algo wrr
lb_kind DR
persistence_timeout 60
protocol TCP
real_server 192.168.1.201 3306 { #本机IP地址
weight 3
notify_down /etc/keepalived/check_mysql.sh #检测到服务down后执行的脚本
TCP_CHECK {
connect_timeout 10 #连接超时
nb_get_retry 3 #重试次数
delay_before_retry 3 #重试间隔时间
connect_port 3306 #mysql端口号
}
}

MySQL-master2


! Configuration File for keepalived
global_defs {
notification_email {
xxx@mail.com
}
notification_email_from xxx@mail.com
smtp_server 127.0.0.1
smtp_connect_timeout 30
router_id MySQL-ha
}

vrrp_instance VI_1 {
state BACKUP
interface eth0
virtual_router_id 51
priority 90
advert_int 1
nopreempt
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
192.168.1.200
}
}

virtual_server 192.168.1.200 3306 {
delay_loop 2
lb_algo wrr
lb_kind DR
persistence_timeout 60
protocol TCP
real_server 192.168.1.202 3306 {
weight 3
notify_down /etc/keepalived/check_mysql.sh
TCP_CHECK {
connect_timeout 10
nb_get_retry 3
delay_before_retry 3
connect_port 3306
}
}

/etc/keepalived/check_mysql.sh

!/bin/sh
pkill keepalived

该脚本能在mysql服务不可用时,停止keepalived,从而不独占虚拟IP地址,保障虚拟地址被其他机器的keepalived抢占

启动keepalived

/etc/init.d/keepalived start | restart | stop

Comments

comments powered by Disqus