Spring JmsTemplate convertAndSend() and receiveAndConvert()

By Arvind Rai, August 23, 2020
This page will walk through convertAndSend() and receiveAndConvert() methods of Spring JmsTemplate class. The JmsTemplate.convertAndSend() method sends the given object to the specified destination converting the object into a JMS message with a configured MessageConverter. The JmsTemplate.receiveAndConvert() receives a message synchronously from given destination and after receiving message, it is converted into an object with a configured MessageConverter. If no message converter is configured, the SimpleMessageConverter is used as default conversion strategy for convertAndSend() and receiveAndConvert() methods.
Here on this page we will discuss using convertAndSend() and receiveAndConvert() methods in detail with examples.

Technologies Used

Find the technologies being used in our example.
1. Java 11
2. Spring 5.2.8.RELEASE
3. Spring Boot 2.3.2.RELEASE
4. Maven 3.5.2

JmsTemplate convertAndSend()

The convertAndSend method sends the given object to the specified destination, converting the object to a JMS message with a configured MessageConverter. We can also pass MessagePostProcessor callback to convertAndSend method. The MessagePostProcessor allows the modification of the message after conversion. If destination is not passed, the message is sent to default destination.
The convertAndSend has following method overloading.
1.
void convertAndSend(Destination destination, Object message) 
Find the code snippet.
Queue tlQueue = jmsTemplate.getConnectionFactory().createConnection().createSession().createQueue("tl");
jmsTemplate.convertAndSend(tlQueue, teamLead); 
The javax.jms.Queue is the subinterface of javax.jms.Destination interface.
2.
void convertAndSend(Destination destination, Object message, MessagePostProcessor postProcessor) 
Find the code snippet.
Queue devQueue = jmsTemplate.getConnectionFactory().createConnection().createSession().createQueue("dev");
jmsTemplate.convertAndSend(devQueue, developer, new MessagePostProcessor() {
	@Override
	public Message postProcessMessage(Message message) throws JMSException {
		message.setJMSMessageID("12345");
		return message;
	}
}); 
3. Message will be sent to default destination.
void convertAndSend(Object message) 
Find the sample code.
jmsTemplate.setDefaultDestinationName("defaultEmpDest");
jmsTemplate.convertAndSend(director); 
4. Message will be sent to default destination.
void convertAndSend(Object message, MessagePostProcessor postProcessor) 
Find the code snippet.
jmsTemplate.convertAndSend(developer, new MessagePostProcessor() {
	@Override
	public Message postProcessMessage(Message message) throws JMSException {
		message.setJMSMessageID("12345");
		return message;
	}
}); 
5.
void convertAndSend(String destinationName, Object message) 
Find the code snippet.
jmsTemplate.convertAndSend("man", manager); 
6.
void convertAndSend(String destinationName, Object message, MessagePostProcessor postProcessor) 
Find the code snippet.
jmsTemplate.convertAndSend(“dev”, developer, new MessagePostProcessor() {
	@Override
	public Message postProcessMessage(Message message) throws JMSException {
		message.setJMSMessageID("12345");
		return message;
	}
}); 

The message sent by convertAndSend method is received by either receiveAndConvert method or JMS listener endpoint. Find the sample JMS listener endpoint.
@JmsListener(destination = "qa")
public void receiveMessage(Employee employee) {
    System.out.println(employee);
} 

JmsTemplate receiveAndConvert()

The receiveAndConvert method receives a message synchronously either from given destination or from default destination and wait only up to a specified time for delivery. After receiving message, it is converted into an object with a configured MessageConverter.
The receiveAndConvert has following method overloading.
1. Receives message from default destination.
Object receiveAndConvert() 
Find the sample code.
Employee emp = (Employee) jmsTemplate.receiveAndConvert(); 
2.
Object receiveAndConvert(Destination destination) 
Find the code snippet.
Employee emp = (Employee) jmsTemplate.receiveAndConvert(tlQueue); 
3.
Object receiveAndConvert(String destinationName) 
Find the code snippet.
Employee emp = (Employee) jmsTemplate.receiveAndConvert("man"); 

Complete Example using Spring Boot

pom.xml
<parent>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-parent</artifactId>
	<version>2.3.2.RELEASE</version>
	<relativePath />
</parent>
<dependencies>
        <dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-activemq</artifactId>
	</dependency>
	<dependency>
		<groupId>org.apache.activemq</groupId>
		<artifactId>activemq-broker</artifactId>
	</dependency>
	<dependency>
		<groupId>com.fasterxml.jackson.core</groupId>
		<artifactId>jackson-databind</artifactId>
	</dependency>
</dependencies> 
JMSConfig.java
package com.concretepage.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.annotation.EnableJms;
import org.springframework.jms.config.DefaultJmsListenerContainerFactory;
import org.springframework.jms.support.converter.MappingJackson2MessageConverter;
import org.springframework.jms.support.converter.MessageConverter;
import org.springframework.jms.support.converter.MessageType;
@Configuration
@EnableJms
public class JMSConfig {
	@Bean
	public DefaultJmsListenerContainerFactory containerFactory() {
		DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
		factory.setSessionTransacted(true);
		factory.setMaxMessagesPerTask(1);
		factory.setConcurrency("1-5");
		return factory;
	}
	@Bean
	public MessageConverter jacksonJmsMessageConverter() {
		MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
		converter.setTargetType(MessageType.TEXT);
		converter.setTypeIdPropertyName("_type");
		return converter;
	}
} 
Employee.java
package com.concretepage;
public class Employee {
	private int id;
	private String profile;
	public Employee() {}
	public Employee(int id, String profile) {
		this.id = id;
		this.profile = profile;
	}	
        //Sets and Gets        

	@Override
	public String toString() {
		return id + ", " + profile;
	}
} 
QaMsgReceiver.java
package com.concretepage.receiver;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;
import com.concretepage.Employee;
@Component
public class QaMsgReceiver {
	@JmsListener(destination = "qa")
	public void receiveMessage(Employee employee) {
           System.out.println(employee);
	}
} 
Application.java
package com.concretepage;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Queue;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.jms.JmsException;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessagePostProcessor;
@SpringBootApplication
public class Application {
	public static void main(String[] args) throws JmsException, JMSException {
		ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);
		JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class);

		// Send and receive from default destination
		jmsTemplate.setDefaultDestinationName("defaultEmpDest");
		Employee director = new Employee(100, "Director");
		jmsTemplate.convertAndSend(director);
		Employee emp1 = (Employee) jmsTemplate.receiveAndConvert();
		System.out.println(emp1);

		// Send and receive from given destination
		Employee manager = new Employee(200, "Manager");
		jmsTemplate.convertAndSend("man", manager);
		Employee emp2 = (Employee) jmsTemplate.receiveAndConvert("man");
		System.out.println(emp2);

		// Send and receive from Queue as destination
		Queue tlQueue = jmsTemplate.getConnectionFactory().createConnection().createSession().createQueue("tl");
		Employee teamLead = new Employee(300, "Team Lead");
		jmsTemplate.convertAndSend(tlQueue, teamLead);
		Employee emp3 = (Employee) jmsTemplate.receiveAndConvert(tlQueue);
		System.out.println(emp3);

		// Using MessagePostProcessor
		Queue devQueue = jmsTemplate.getConnectionFactory().createConnection().createSession().createQueue("dev");
		Employee developer = new Employee(400, "Developer");
		jmsTemplate.convertAndSend(devQueue, developer, new MessagePostProcessor() {
			@Override
			public Message postProcessMessage(Message message) throws JMSException {
				message.setJMSMessageID("12345");
				return message;
			}
		});
		Employee emp4 = (Employee) jmsTemplate.receiveAndConvert(devQueue);
		System.out.println(emp4);
		
		// Sending object to listen using @JmsListener
		Employee qaEngineer = new Employee(500, "QA Engineer");
		jmsTemplate.convertAndSend("qa", qaEngineer);
	}
} 
Find the print screen of the output in Eclipse console.
Spring JmsTemplate convertAndSend() and receiveAndConvert()

References

Spring JmsTemplate
JMS (Java Message Service)

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI







©2024 concretepage.com | Privacy Policy | Contact Us