This example shows you how to configure and use message groups with ActiveMQ.
Message groups are sets of messages that has the following characteristics:
You can make any message belong to a message group by setting its 'JMXGroupID' string property to the group id. In this example we create a message group 'Group-0'. And make such a message group of 10 messages. It also create two consumers on the queue where the 10 'Group-0' group messages are to be sent. You can see that with message grouping enabled, all the 10 messages will be received by the first consumer. The second consumer will receive none.
Alternatively, ActiveMQ's connection factories can be configured to auto group messages. By setting autogroup
to true on the ActiveMQConnectionFactory
(or setting <autogroup>true</autogroup>
in activemq-jms.xml
's connection factory settings), a random unique id
will be picked to create a message group. Every messages sent by a producer created from this connection factory will automatically
be part of this message group.
To run the example, simply type mvn verify -Pexample
from this directory
client-jndi.properties
file in the directory ../common/config
InitialContext initialContext = getContext();
Queue queue = (Queue) initialContext.lookup("/queue/exampleQueue");
ConnectionFactory cf = (ConnectionFactory) initialContext.lookup("/ConnectionFactory");
connection = cf.createConnection();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer messageProducer = session.createProducer(topic);
MessageConsumer consumer1 = session.createConsumer(queue);
consumer1.setMessageListener(new SimpleMessageListener("consumer-1"));
MessageConsumer consumer2 = session.createConsumer(queue);
consumer2.setMessageListener(new SimpleMessageListener("consumer-2"));
int msgCount = 10;
TextMessage[] groupMessages = new TextMessage[msgCount];
for (int i = 0; i < msgCount; i++)
{
groupMessages[i] = session.createTextMessage("Group-0 message " + i);
groupMessages[i].setStringProperty("JMSXGroupID", "Group-0");
producer.send(groupMessages[i]);
System.out.println("Sent message: " + groupMessages[i].getText());
}
connection.start();
String trueReceiver = messageReceiverMap.get(groupMessages[0].getText());
for (TextMessage grpMsg : groupMessages)
{
String receiver = messageReceiverMap.get(grpMsg.getText());
if (!trueReceiver.equals(receiver))
{
System.out.println("Group message [" + grpMsg.getText() + "[ went to wrong receiver: " + receiver);
result = false;
}
}
finally
block. Closing a JMS connection will automatically close all of its sessions, consumers, producer and browser objects
finally
{
if (initialContext != null)
{
initialContext.close();
}
if (connection != null)
{
connection.close();
}
}