1. 程式人生 > >十、使用HAProxy為RabbitMQ做負載均衡

十、使用HAProxy為RabbitMQ做負載均衡

安裝HAProxy

# 安裝HAProxy
yum install haproxy

# 檢視版本
haproxy -v

配置HAProxy

# 進入配置檔案目錄
cd /etc/haproxy

# 修改配置檔案
vi haproxy.cfg

檔案內容如下:

global
    log         127.0.0.1 local2
    pidfile     /var/run/haproxy.pid
    maxconn     4000
    daemon

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                 3000

listen private_monitoring
    bind 0.0.0.0:8100
    mode http
    option httplog
    stats enable
    stats uri /stats
    stats refresh 10s
    stats auth admin:admin

listen rabbitmq_cluster
    bind 0.0.0.0:5672
    mode tcp
    option tcplog
    option clitcpka
    balance roundrobin
    server rabbitmq_01 192.168.0.101:5672 check inter 5000 rise 2 fall 3
    server rabbitmq_02 192.168.0.102:5672 check inter 5000 rise 2 fall 3
    server rabbitmq_03 192.168.0.103:5672 check inter 5000 rise 2 fall 3

listen rabbitmq_admin
    bind 0.0.0.0:15672
    server rabbitmq_admin_01 192.168.0.101:15672
    server rabbitmq_admin_02 192.168.0.102:15672
    server rabbitmq_admin_03 192.168.0.103:15672

啟動HAProxy 

# 啟動HAProxy
haproxy -f /etc/haproxy/haproxy.cfg -d

開通防火牆埠:

  • HAProxy監控埠:8100
  • RabbitMQ負載均衡埠:5672
  • RabbitMQ管理頁面:15672

檢視結果 

HAProxy監控頁面:

RabbitMQ管理頁面:

測試

修改配置檔案中的地址:

spring:
  #訊息佇列配置
  rabbitmq:
    host: 192.168.0.104 #HAProxy的地址
    port: 5672
    username: guest
    password: guest
    virtual-host: /
    publisher-returns: true
    publisher-confirms: true
    connection-timeout: 5000ms

釋出訊息:

ConfirmCallback -> 訊息釋出到交換器成功,id:CorrelationData [id=3e27f443-bcb0-4690-b72c-cf6a66761fd1]

接收訊息:

2019-04-30 00:08:45.676  INFO 49016 --- [cTaskExecutor-1] cc.yesway.service.DirectQueueListener    :