千家信息网

Haproxy+Keepalived+MySQL实现读均衡负载

发表于:2025-01-20 作者:千家信息网编辑
千家信息网最后更新 2025年01月20日,环境说明:本系统对数据安全性不高,TPS操作很低,主要是查询的环境。本方案架构图如下: 应用服务器对只读的应用程序连接虚拟IP地址,连接到haproxy,然后通过haproxy将TCP协议转移到下面的
千家信息网最后更新 2025年01月20日Haproxy+Keepalived+MySQL实现读均衡负载

环境说明:

本系统对数据安全性不高,TPS操作很低,主要是查询的环境。
本方案架构图如下: 应用服务器对只读的应用程序连接虚拟IP地址,连接到haproxy,然后通过haproxy将TCP协议转移到下面的3个数据库服务器中。Haproxy在此做4层的TCP交换服务。keepalived为了防止haproxy单点故障。 为什么不用LVS? 我们的环境服务器少,haproxy和lvs相比性能差不多,且haproxy自带有mysql check,不需要额外的写mysql侦测脚本。


1.haproxy安装


下载地址:http://www.haproxy.org/download/1.5/src/haproxy-1.5.5.tar.gz
依赖包安装:#yum install gcc gcc-c++ make zlib-devel bzip2-devel openssl-devel

安装pcre,自带的pcre-7.8-3.1.el6.x86_64貌似版本低了,导致无法安装proxy
#tar xzvf pcre-8.34.tar.gz
#cd pcre-8.34#./configure --prefix=/usr \--docdir=/usr/share/doc/pcre-8.34 \--enable-utf --enable-unicode-properties \--enable-pcregrep-libz --enable-pcregrep-libbz2#make#make check#make install

script "/etc/keepalived/check_haproxy.sh" interval 2 weight 2

global_defs { router_id LVS_DEVEL }
vrrp_instance VI_1 { state MASTER interface bond0 virtual_router_id 51 priority 150 advert_int 1 authentication { auth_type PASS auth_pass 1111 } track_script { chk_http_port } virtual_ipaddress { 192.168.231.18 } }}
配置侦测haproxy状态脚本:#vi /etc/keepalived/check_haproxy.sh#!/bin/bashA=`ps -C haproxy --no-header |wc -l`if [ $A -eq 0 ];then /usr/local/sbin/haproxy -f /etc/haproxy/haproxy.confsleep 3
if [ `ps -C haproxy --no-header |wc -l` -eq 0 ];then /etc/init.d/keepalived stopfifi
启动keepalived服务:# /etc/init.d/keepalived start

添加新的协议地址:#ip add[root@mss-dn03 ~]# ip add1: lo: mtu 16436 qdisc noqueue state UNKNOWN link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 inet 127.0.0.1/8 scope host lo inet6 ::1/128 scope host valid_lft forever preferred_lft forever2: eth0: mtu 1500 qdisc mq state DOWN qlen 1000 link/ether 90:e2:ba:23:87:04 brd ff:ff:ff:ff:ff:ff3: eth2: mtu 1500 qdisc mq state DOWN qlen 1000 link/ether 90:e2:ba:23:87:05 brd ff:ff:ff:ff:ff:ff
9: bond0: mtu 1500 qdisc noqueue state UP link/ether 6c:ae:8b:26:52:3b brd ff:ff:ff:ff:ff:ff inet 192.168.231.7/24 brd 192.168.231.255 scope global bond0 inet6 fe80::6eae:8bff:fe26:523b/64 scope link tentative dadfailed valid_lft forever preferred_lft forever
设置开启自启动:# chkconfig --level 0123456 keepalived on# chkconfig --list keepalived

测试过程中发现,master宕机后,VIP需要几十秒才能ping通,切换很慢:arping -I bond0 -c 5 -s VIP GATEWAY# arping -I bond0 -c 5 -s 192.168.231.18 192.168.231.254


Getting started with HAProxy and MySQL replication(能实现读写路由):
http://blog.yannickjaquier.com/linux/getting-started-with-haproxy-and-mysql-replication.html Haproxy配置日志: http://www.linuxidc.com/Linux/2012-06/63585.htm

来自为知笔记(Wiz)

0