I am using the Spring API's JmsTemplate
and MappingJackson2MessageConverter
(version: spring-jms-4.3.4.RELEASE.jar
) to publish messages
to an ActiveMQ topic as shown in the below code.
TopicPublisher class:
@Component
public class TopicPublisher {
@Autowired
private JmsTemplate jmsTemplate;
@Autowired
private MessageConverter messageConverter;
public void send() {
Product product = new Product();
product.setName("abcd");
product.setPrice(10);
jmsTemplate.setMessageConverter(messageConverter);
jmsTemplate.convertAndSend("product.topic", product);
}
}
MappingJackson2MessageConverter class:
@Configuration
public class JMSTextMessageConverter {
@Bean
public MessageConverter jacksonJmsMessageConverter() {
MappingJackson2MessageConverter mappingJackson2MessageConverter
= new MappingJackson2MessageConverter();
mappingJackson2MessageConverter.setTargetType(MessageType.TEXT);
mappingJackson2MessageConverter.setTypeIdPropertyName("_type");
return mappingJackson2MessageConverter;
}
}
Now, I want to set few custom headers to the JMS message being published to the topic. I googled and could not find any example which does this. Can you help ?
The JmsTemplate is a central class from the Spring core package. It simplifies the use of JMS and gets rid of boilerplate code. It handles the creation and release of JMS resources when sending or receiving messages. Let’s create a code sample that shows how to configure the Spring JmsTemplate.
Maven Dependency In order to use Spring JMS in our application, we need to add necessary artifacts in the pom.xml: The newest version of the artifact can be found here. 3. The JmsTemplate JmsTemplate class handles the creation and releasing of resources when sending or synchronously receiving messages.
Default is Point-to-Point (Queues). For JmsTemplate102, this tells the JMS provider which class hierarchy to use in the implementation of the various execute methods. For JmsTemplate itself, it does not affect execute methods. In both implementations, it tells what type of destination to create if dynamic destinations are enabled.
It will also provide a property called defaultDestination – which will be used with send and receive operations that do not refer to a specific destination. 6. Message Conversion Spring JMS would be incomplete without the support of Message Converters.
You can add custom properties by using convertAndSend
method from JmsTemplate
by sending MessagePostProcessor
as shown below:
jmsTemplate.convertAndSend("product.topic", product, new MessagePostProcessor() {
@Override
public Message postProcessMessage(Message message) throws JMSException {
message.setStringProperty("my_property", "my_value");
return message;
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With