持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第28天,点击查看活动详情
我们之前搭建的镜像集群,已经具备了集群的功能,请求发送到任何一个节点上,数据都是在集群内共享的。
但是,在企业使用时,通常还会选择在集群基础上增加负载均衡的能力。即希望将客户端的请求能够尽量均匀的分配到集群中各个节点上,这样可以让集群的压力得到平衡。
实现负载均衡的方式有很多,HAProxy就是其中一种可选方案。HAProxy是一个免费、快速并且可靠的解决方案,有很多大型互联网公司都在使用。通过HAProxy,应用可以直连一个单一的IP地址,然后HAProxy会将这个IP地址的TCP请求进行转发,并在转发过程中实现负载均衡。
安装
#安装
yum install haproxy
#检测安装是否成功
haproxy
#查找haproxy.cfg文件的位置
find / ‐name haproxy.cfg
#配置haproxy.cfg文件 后面会列出参考配置
vim /etc/haproxy/haproxy.cfg
#启动haproxy
haproxy ‐f /etc/haproxy/haproxy.cfg
#查看haproxy进程状态
systemctl status haproxy.service
#状态如下说明 已经启动成功 Active: active (running)
#访问如下地址对mq节点进行监控
http://localhost:1080/haproxy_stats
#代码中访问mq集群地址,则变为访问haproxy地址:5672
配置
修改haproxy.cfg文件。下面是参考配置。注意将节点的IP地址和端口换成你自己的环境。
#全局设置
global
log 127.0.0.1 local2
chroot /var/lib/haproxy
pidfile /var/run/haproxy.pid
maxconn 4000
user haproxy
group haproxy
daemon
# turn on stats unix socket
stats socket /var/lib/haproxy/stats
defaults
mode http
log global
option httplog
option dontlognull
option http‐server‐close
option forwardfor except 127.0.0.0/8
option redispatch
retries 3
timeout http‐request 10s
timeout queue 1m
timeout connect 10s
timeout client 1m
timeout server 1m
timeout http‐keep‐alive 10s
timeout check 10s
maxconn 300059
#对MQ集群进行监听
listen rabbitmq_cluster
bind 0.0.0.0:5672
option tcplog
mode tcp
option clitcpka
timeout connect 1s
timeout client 10s
timeout server 10s
balance roundrobin
server node1 centos1:5672 check inter 5s rise 2 fall 3
server node2 centos2:5672 check inter 5s rise 2 fall 3
server node3 centos3:5672 check inter 5s rise 2 fall 3
#开启haproxy监控服务
listen http_front
bind 0.0.0.0:1080
stats refresh 30s
stats uri /haproxy_stats
stats auth admin:admin