MySQL的高可用方案一般有如下几种:
keepalived+双主,MHA,MMM,Heartbeat+DRBD,PXC,Galera Cluster
比较常用的是keepalived+双主,MHA和PXC。
对于小公司,一般推荐使用keepalived+双主,简单。
下面来部署一下
配置环境:
角色 主机IP 主机名 操作系统版本 软件版本
VIP 192.168.244.10
master1 192.168.244.145 master1 CentOS7.1 MySQL 5.6.26,Keepalived v1.2.13
master2 192.168.244.146 master2 CentOS7.1 MySQL 5.6.26,Keepalived v1.2.13
一、 配置MySQL双主复制环境
1. 修改配置文件
master1中有关复制的配置如下:
[mysqld] log-bin=mysql-bin server-id=1 log_slave_updates=1
master2
[mysqld] log-bin=mysql-bin server-id=2 log_slave_updates=1 read_only=1
2. 创建复制用户
master1中创建:
CREATE USER 'repl'@'192.168.244.146' IDENTIFIED BY 'mysql'; GRANT REPLICATION SLAVE ON *.* TO 'repl'@'192.168.244.146';
master2中创建:
CREATE USER 'repl'@'192.168.244.145' IDENTIFIED BY 'mysql'; GRANT REPLICATION SLAVE ON *.* TO 'repl'@'192.168.244.145';
3. 执行CHANGE MASTER TO语句
因是从头搭建MySQL主从复制集群,所以不需要获取全局读锁来得到二进制日志文件的位置,直接根据show master status的输出来确认。
master1上执行:
CHANGE MASTER TO MASTER_HOST='192.168.244.146', MASTER_USER='repl', MASTER_PASSWORD='mysql', MASTER_LOG_FILE='mysql-bin.000004', MASTER_LOG_POS=64729;
master2上执行:
CHANGE MASTER TO MASTER_HOST='192.168.244.145', MASTER_USER='repl', MASTER_PASSWORD='mysql', MASTER_LOG_FILE='mysql-bin.000003', MASTER_LOG_POS=68479;
4. 分别在两个节点上执行start slave语句并通过show slave status\G查看复制是否搭建成功。
成功标准:
Slave_IO_Running: Yes Slave_SQL_Running: Yes
二、 配置Keepalived
1. 安装Keepalived
# yum install -y keepalived
当然,也可直接编译官方的源码包。
2. 修改Keepalived的配置文件
master1
[root@master1 ~]# vim /etc/keepalived/keepalived.conf
vrrp_script chk_mysql { script "/etc/keepalived/check_mysql.sh" interval 30 #设置检查间隔时长,可根据自己的需求自行设定 } vrrp_instance VI_1 { state BACKUP #通过下面的priority来区分MASTER和BACKUP,也只有如此,底下的nopreempt才有效 interface eno16777736 virtual_router_id 51 priority 100 advert_int 1 nopreempt #防止切换到从库后,主keepalived恢复后自动切换回主库 authentication { auth_type PASS auth_pass 1111 } track_script { chk_mysql } virtual_ipaddress { 192.168.244.10/24 } }
关于keepalived的参数的详细介绍,可参考:LVS+Keepalived搭建MyCAT高可用负载均衡集群
其中,/etc/keepalived/check_mysql.sh内容如下