ActiveMQ中如何实现集群和负载均衡?

ActiveMQ 中可以通过以下方式实现集群和负载均衡:
1、 集群:

  • 使用 Master-Slave 模式,一个 Master 节点和多个 Slave 节点:
<broker xmlns="http://activemq.apache.org/schema/core" brokerName="master" dataDirectory="${activemq.data}">
   <persistenceAdapter>...</persistenceAdapter>
</broker>  

<broker xmlns="http://activemq.apache.org/schema/core" brokerName="slave1"  masterConnectorURI="tcp://master:61616"  dataDirectory="${activemq.data}">
</broker>

<broker xmlns="http://activemq.apache.org/schema/core" brokerName="slave2"  masterConnectorURI="tcp://master:61616" dataDirectory="${activemq.data}"> 
</broker>
  • 使用 NetworkConnector 互联多个 Broker 节点:
<networkConnectors>     
  <networkConnector duplex="true" uri="static:(tcp://node1:61616,tcp://node2:61616)"/> 
</networkConnectors>

此设置会使 node1 和 node2 两个节点互联,实现集群。

2、 负载均衡:

  • 发送端使用多个生产者实例向不同 Broker 发送消息:
Connection conn1 = cf.createConnection(); 
Connection conn2 = cf.createConnection();   

Session sess1 = conn1.createSession(false, Session.AUTO_ACKNOWLEDGE);
Session sess2 = conn2.createSession(false, Session.AUTO_ACKNOWLEDGE);

MessageProducer prod1 = sess1.createProducer(queue);
MessageProducer prod2 = sess2.createProducer(queue);

prod1.send(msg);  // 发送到 node1
prod2.send(msg);  // 发送到 node2
  • 消费端使用多个消费者实例从不同 Broker 消费消息:
Connection conn1 = cf.createConnection(); 
Connection conn2 = cf.createConnection();   

Session sess1 = conn1.createSession(false, Session.AUTO_ACKNOWLEDGE);
Session sess2 = conn2.createSession(false, Session.AUTO_ACKNOWLEDGE);   

MessageConsumer cons1 = sess1.createConsumer(queue); 
MessageConsumer cons2 = sess2.createConsumer(queue);

Message msg1 = cons1.receive(); // 消费 node1 的消息
Message msg2 = cons2.receive(); // 消费 node2 的消息