This example demonstrates a JMS queue deployed on two different nodes. The two nodes are configured to form a cluster.
We then create a consumer on the queue on each node, and we create a producer on only one of the nodes.
We then send some messages via the producer, and we verify that both consumers receive the sent messages in a round-robin fashion.
In other words, ActiveMQ load balances the sent messages across all consumers on the cluster
This example uses JNDI to lookup the JMS Queue and ConnectionFactory objects. If you prefer not to use JNDI, these could be instantiated directly.
Here's the relevant snippet from the server configuration, which tells the server to form a cluster between the two nodes and to load balance the messages between the nodes.
<cluster-connection name="my-cluster">
<address>jms</address>
<connector-ref>netty-connector</connector-ref>
<retry-interval>500</retry-interval>
<use-duplicate-detection>true</use-duplicate-detection>
<forward-when-no-consumers>true</forward-when-no-consumers>
<max-hops>1</max-hops>
<discovery-group-ref discovery-group-name="my-discovery-group"/>
</cluster-connection>
For more information on ActiveMQ load balancing, and clustering in general, please see the clustering section of the user manual.
To run the example, simply type mvn verify
from this directory
ic0 = getContext(0);
Queue queue = (Queue)ic0.lookup("/queue/exampleQueue");
ConnectionFactory cf0 = (ConnectionFactory)ic0.lookup("/ConnectionFactory");
ic1 = getContext(1);
ConnectionFactory cf1 = (ConnectionFactory)ic1.lookup("/ConnectionFactory");
connection0 = cf0.createConnection();
connection1 = cf1.createConnection();
Session session0 = connection0.createSession(false, Session.AUTO_ACKNOWLEDGE);
Session session1 = connection1.createSession(false, Session.AUTO_ACKNOWLEDGE);
connection0.start();
connection1.start();
MessageConsumer consumer0 = session0.createConsumer(queue);
MessageConsumer consumer1 = session1.createConsumer(queue);
MessageProducer producer = session0.createProducer(queue);
final int numMessages = 10;
for (int i = 0; i < numMessages; i++)
{
TextMessage message = session0.createTextMessage("This is text message " + i);
producer.send(message);
System.out.println("Sent message: " + message.getText());
}
for (int i = 0; i < numMessages; i += 2)
{
TextMessage message0 = (TextMessage)consumer0.receive(5000);
System.out.println("Got message: " + message0.getText() + " from node 0");
TextMessage message1 = (TextMessage)consumer1.receive(5000);
System.out.println("Got message: " + message1.getText() + " from node 1");
}
finally
block. Closing a JMS connection will automatically close all of its sessions, consumers, producer and browser objects
finally
{
if (connection0 != null)
{
connection0.close();
}
if (connection1 != null)
{
connection1.close();
}
}