
准备条件
安装haproxy
yum install -y haproxy
创建配置文件
mkdir -p /usr/local/config/haproxy
cd /usr/local/config/haproxy
vim haproxy.cfg
添加配置内容
global
log 127.0.0.1 local2
chroot /var/lib/haproxy
pidfile /var/run/haproxy.pid
maxconn 4000
user haproxy
group haproxy
daemon
defaults
log global
mode tcp
option tcplog
option dontlognull
retries 3
option redispatch
maxconn 2000
timeout connect 5s
timeout client 120s
timeout server 120s
listen rabbitmq_cluster
bind 0.0.0.0:5671
mode tcp
balance roundrobin
server rabbitmq_node1 172.16.140.130:5672 check inter 5000 rise 2 fall 2
server rabbitmq_node2 172.16.140.131:5672 check inter 5000 rise 2 fall 2
server rabbitmq_node3 172.16.140.132:5672 check inter 5000 rise 2 fall 2
listen monitor
bind 0.0.0.0:8100
mode http
option httplog
stats enable
stats uri /stats
stats refresh 5s
启动haproxy
haproxy -f /usr/local/config/haproxy/haproxy.cfg
在代码中连接rabbitmq需要填写的地址为haproxy所在的地址,端口号为rabbitmq_cluster中配置的地址
可以通过monitor中8100的端口查看当前服务的状态
在使用了haproxy之后,我们达成了负载均衡的目的,但是如果只是一个haproxy的话,那么当haproxy宕机,那么整个rabbitmq都会处于不可用状态,所以我们需要使用keepalived来实现主备模式
准备工作
效果预期:对两台haproxy提供主备的模式
安装keepalived
yum install -y keepalived
安装完成后,在/etc/keepalived/中有文件keepalived.conf文件,将原有的备份,新建一份配置文件。
配置配置文件
global_defs { #全局配置
router_id lb01 #标识身份->名称
}
vrrp_instance VI_HAPROXY {
state MASTER #标识角色状态
interface ens160 #网卡绑定接口
virtual_router_id 51 #虚拟路由id
priority 150 #优先级
advert_int 1 #监测间隔时间
authentication { #认证
auth_type PASS #认证方式
auth_pass 1111 #认证密码
}
virtual_ipaddress {
172.16.140.167 #虚拟的VIP地址
}
}
启动keepalived
systemctl start keepalived
systemctl enable keepalived
备机上也需要操作上面步骤,不同的是配置文件
global_defs {
router_id lb02
}
vrrp_instance VI_1 {
state BACKUP
interface ens160
virtual_router_id 51
priority 100
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
172.16.140.167
}
}
查看keepalived日志
tail -f /var/log/messages -n 200