In this post I’m going to show you how to configure a JMS message selector using Spring JMS.
You’ll also see how to add information to a message so that you can select it.
So here we go.
If you want to learn more about Spring JMS - head on over to the Spring JMS tutorials page.
1. What is a JMS Message Selector?
If your messaging application needs to filter the messages it receives, you can use a JMS message selector. It allows a message consumer to specify the messages it is interested in.
A selector is a String that contains an expression. The syntax of the expression is based on a subset of the SQL92 conditional expression syntax.
Let’s create an example to show how all of this works. We start from a previous Spring JMS configuration example.
We then modify the
Receiver so that it receives high and low priority messages with different listeners. In the
Sender we add a JMS property on which we can filter.
2. General Project Overview
We will use the following tools/frameworks:
- Spring JMS 5.1
- Spring Boot 2.1
- ActiveMQ 5.14
- Maven 3.5
Our project has the following directory structure:
3. Add a JMS Message Selector to a Listener
@JmsListener there is an optional message selector property you can define.
We create two listeners in the
Receiver: one for high priority messages and one for low priority messages. Selection is done based on a priority JMS property that we will set in the
Note that a message consumer receives only messages whose headers and properties match the selector.
A message selector cannot select messages on the basis of the content of the message body.
JmsTemplate by default converts a String into a
TextMessage using the
SimpleMessageConverter. For more information on this you can check the Spring JMS MessageConverter example.
We can use a MessagePostProcessor to add a JMS property to a message after it has been processed by the converter.
Sender to check an
isHighPriority parameter. If the value equals true, a priority property with the value high is set. Otherwise the property is set to low.
4. Test the Message Filter
We modify the existing test case so that three messages are sent.
Two of them are high priority and will lower the
CountDownLatch in the
Open a command prompt in the root directory and start the test case.
In the output logs, we can see that the messages are received in the respective JMS Listeners.
If you would like to run the above code sample you can get the full source code here.
Setting up a JMS message selector is straightforward when you use Spring JMS.
Make sure to leave a comment if the example was helpful.