Few hours ago I’ve found an usefull post about preserving message order with ActiveMQ written by Marcelo Jabali from FUSE Source.

In his example Marcelo used broker feature called Exclusive Consumers. It lets send messages only to one consumer and if it fails then second consumer gets all messages. I think it is not the best idea if we have many messages to process. Why we wouldn’t use few consumers with preserved message order? Well, I was sure it is not possible, but during last training I’ve found solution.

Broker configuration

So how to force ActiveMQ to preserve message order? It’s really simple, we just need to change dispatch policy for destination. We can do this for all queues or only for selected. [xml]

\[/xml\]

After this consumers should receive messages in same order like they were sent from producer. You can find example code on github: example-activemq-ordered. You can run all from maven: [bash] cd broker1; mvn activemq:run cd broker2; mvn activemq:run cd consumer; mvn camel:run cd consumer; mvn camel:run cd producer; mvn camel:run [/bash]

Upgrade

After posting update about this blog post to Twitter Dejan Bosanac send me few updates. He is co-author of ActiveMQ in Action so his knowledge is much more deeper than mine. :) First of all I mixed XML syntax. strictOrderDispatchPolicy is handled by topics, not queues. For second destination type strict order is turned on by strictOrderDispatch attribute set to true for policyEntry element. This preserves order but, as Dejan wrote, it will broke round robin and all messages will go to only one consumer, as in previous example given by Marcelo.

Also, Marcelo published second post about Message Groups which allows to preserve order and have multiple concurrent consumers on queue.