首先,大家需要在每台MySQL服务器上安装并启用Keepalived。这里使用CentOS 7.0为例:
yum install keepalived -y # 安装 keepalived systemctl enable keepalived && systemctl start keepalived # 启动 keepalived
接着,大家需要创建MySQL主从复制。通过在主服务器上执行以下命令,创建同步用户并授权:
CREATE USER 'repl'@'%' IDENTIFIED BY 'password'; GRANT REPLICATION SLAVE ON *.* TO 'repl'@'%'; FLUSH PRIVILEGES; FLUSH TABLES WITH READ LOCK; SHOW MASTER STATUS; # 记录下File, Position信息,备用
然后,在从服务器上执行以下命令,连接到主服务器并启动复制:
CHANGE MASTER TO MASTER_HOST='master_host_name', MASTER_USER='repl', MASTER_PASSWORD='password', MASTER_LOG_FILE='recorded_file_name', MASTER_LOG_POS=recorded_position; START SLAVE;
接下来,大家需要在每台MySQL服务器上安装HAProxy。这里也使用CentOS 7.0为例:
yum install haproxy -y # 安装 haproxy systemctl enable haproxy && systemctl start haproxy # 启动 haproxy
最后,在HAProxy服务器上创建MySQL负载均衡,并配置Keepalived:
global log 127.0.0.1 local0 log 127.0.0.1 local1 notice maxconn 4096 defaults log global mode http option tcplog option dontlognull retries 3 timeout connect 3s timeout client 30s timeout server 30s listen mysql-replication bind *:3306 mode tcp balance roundrobin option mysql-check user haproxy_check server slave1 slave1_ip:3306 check port 3306 inter 3s server slave2 slave2_ip:3306 check port 3306 inter 3s vrrp_script chk_haproxy { script "/usr/bin/killall -0 haproxy" interval 2 } vrrp_instance VI_1 { interface eth0 state MASTER virtual_router_id 51 priority 101 virtual_ipaddress { haproxy_vip } authentication { auth_type PASS auth_pass keepalived_password } track_script { chk_haproxy } }
其中,mysql-replication为HAProxy监听的端口,haproxy_check为连接mysql的用户,slave1、slave2为MySQL从服务器的IP地址,haproxy_vip为HAProxy的虚拟IP地址,keepalived_password为Keepalived的密码。
通过上述步骤,大家就实现了一个基于Keepalived、MySQL和HAProxy的高可用性方案,保证了MySQL数据库的可靠运行。