Tuesday, November 2, 2010

ActiveMQ - Les wilcards

I've discovered today an interesting new functionality on ActiveMQ.
This is the "Wildcards"


Consumer
From a consumer point of view, it's possible thanks to some special characters to consume messages from several destinations (queues and topics) with only one consumer.

ActiveMQ cuts the destination's name in elements. Those elements are delimited by a dot (.).
For example, the below destinations have 3 elements :

- queue.france.rennes
- queue.france.paris



Here are the special characters:
- . used to separate elements
- * used to match one element
- > used to match one or all trailing elements


For example, to consume all message for France, we can use the below consumer

String brokerURI = ActiveMQConnectionFactory.DEFAULT_BROKER_URL;
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerURI);
Connection connection = connectionFactory.createConnection();
connection.start();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Queue france = session.createQueue("*.france.*");
MessageConsumer consumer = session.createConsumer(france);
Message message = consumer.receive();

or

Queue france = session.createQueue("*.france.>");

Producer
Conversely, the messages producer can send one message to several destinations (then we talk about broadcast). This is n messages, stricly identicaly sent to n destinations.
This avoids to create multiple producers for doing the same sending.

We talk about composite destinations.

Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Queue compositeDestination = session.createQueue("queue.france.rennes, queue.france.paris");
MessageProducer producer = session.createProducer(compositeDestination);
Message message = session.createStreamMessage() ;
producer.send(message);

Notice : we have several independant messages with excalty the same content (header and body).
Careful, a composite destination named "queue.france.*" will not send the messages to all the queues, but to a queue named "queue.france.*".


Conclusion
ActiveMQ wilcards are very powerful with a very simple syntax and use.
Careful, this is not JMS compliant at all, but 100% ActiveMQ specific.


Talk you later.

1 comment:

sap test said...

I had no clue about ActiveMQ but after reading your post I understand it in much easier way. I faced some problems while implemented the code in first go but second time it worked perfectly. The code will take time to learn. Thanks for the information. Keep it up.