producerConnection.setMessagePrioritySupported(true);
producerConnection.start();
final Session producerSession = producerConnection.createSession(true, Session.SESSION_TRANSACTED);
MessageProducer producer = producerSession.createProducer(dest);
ActiveMQMessageConsumer consumer;
// Create consumer on separate connection
ActiveMQConnection consumerConnection = (ActiveMQConnection) cf.createConnection();
consumerConnection.setMessagePrioritySupported(true);
consumerConnection.start();
final ActiveMQSession consumerSession = (ActiveMQSession) consumerConnection.createSession(true,
Session.SESSION_TRANSACTED);
consumer = (ActiveMQMessageConsumer) consumerSession.createConsumer(dest);
// Produce X number of messages with a session commit after each message
Random random = new Random();
for (int i = 0; i < messageCount; ++i) {
Message message = producerSession.createTextMessage("Test message #" + i);
producer.send(message, DeliveryMode.PERSISTENT, random.nextInt(10), 45*1000);
producerSession.commit();
}
producer.close();
// ***************************************************
// If we create the consumer here instead of above, the
// the messages will be consumed in priority order
// ***************************************************
//consumer = (ActiveMQMessageConsumer) consumerSession.createConsumer(dest);
// Consume all of the messages we produce using a listener.
// Don't exit until we get all the messages.
final CountDownLatch latch = new CountDownLatch(messageCount);
final StringBuffer failureMessage = new StringBuffer();
consumer.setMessageListener(new MessageListener() {
int lowestPrioritySeen = 10;
boolean firstMessage = true;
public void onMessage(Message msg) {
try {
int currentPriority = msg.getJMSPriority();
LOG.debug(currentPriority + "<=" + lowestPrioritySeen);
// Ignore the first message priority since it is prefetched
// and is out of order by design
if (firstMessage == true) {
firstMessage = false;
LOG.debug("Ignoring first message since it was prefetched");
} else {
// Verify that we never see a priority higher than the
// lowest
// priority seen
if (lowestPrioritySeen > currentPriority) {
lowestPrioritySeen = currentPriority;
}
if (lowestPrioritySeen < currentPriority) {
failureMessage.append("Incorrect priority seen (Lowest Priority = " + lowestPrioritySeen
+ " Current Priority = " + currentPriority + ")"
+ System.getProperty("line.separator"));
}
}
} catch (JMSException e) {
e.printStackTrace();
} finally {
latch.countDown();
LOG.debug("Messages remaining = " + latch.getCount());
}
}
});
latch.await();
consumer.close();
// Cleanup producer resources
producerSession.close();
producerConnection.stop();
producerConnection.close();