jms

JMS Message Types Example

JMS Message represents the payload it encapsulates so based on the kind of payload it carries we have many flavors of message types..

JMS defines five types of messages. Each of these derives from the Message interface.

Based on the kind of payload one wants to send, one can chose the message type.

One thing to note is that Message type is an interface thus JMS leaves the responsibility of implementing the interface to the JMS providers. This is in a way good as the JMS vendors can implement the messages in their own way.

The five message types are:

  1. Message
  2. TextMessage
  3. BytesMessage
  4. ObjectMessage
  5. StreamMessage
  6. MapMessage

1. Dependencies

In order to send and receive JMS messages to and from a JMS message broker, we need to include the message service library. In this example we are using activeMq so our pom.xml will have dependencies related to spring as well as activeMq.

pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.javacodegeeks.camel</groupId>
	<artifactId>springQuartzScheduler</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>4.1.5.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>4.1.5.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jms</artifactId>
			<version>4.1.5.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.apache.activemq</groupId>
			<artifactId>activemq-all</artifactId>
			<version>5.12.0</version>
		</dependency>
	</dependencies>
	
</project>

2. Empty Message

The simplest type of message is an empty message which just contains JMS Headers and properties. An empty message type can be created by simply calling createMessage() on session object.

Message msg = session.createMessage();
msg.setBooleanProperty("isPayloadEmpty", true);

This type of message contains only JMS headers and properties, and is used in event notification. In our example, we will set a boolean property isPayloadEmpty to true and will make sure consumer receives the message with the property set to true.

In sendEmptyMessage(), we create an empty message send it using spring JmsTemplate.

JmsProducer:

package com.javacodegeeks.spring.jms;

import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;

import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;

public class JmsProducer {
	private JmsTemplate jmsTemplate;
	private Destination destination;
	
	public JmsTemplate getJmsTemplate() {
		return jmsTemplate;
	}

	public void setJmsTemplate(JmsTemplate jmsTemplate) {
		this.jmsTemplate = jmsTemplate;
	}
	
	public Destination getDestination() {
		return destination;
	}

	public void setDestination(Destination destination) {
		this.destination = destination;
	}

	public void sendEmptyMessage() {
		System.out.println("Producer sends empty message");
		jmsTemplate.send(destination, new MessageCreator() {
			public Message createMessage(Session session) throws JMSException {
				Message msg = session.createMessage();
				msg.setBooleanProperty("isPayloadEmpty", true);
				return msg;
			}});		
	}
}

In the consumer class, in receiveEmptyMessage(), we receive the empty message using spring JmsTemplate. We check whether the message is not null an has isPayloadEmpty set to true.

JmsConsumer:

package com.javacodegeeks.spring.jms;

import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.TextMessage;

import org.springframework.jms.core.JmsTemplate;

public class JmsConsumer {
	private JmsTemplate jmsTemplate;
	private Destination destination;
	
	public JmsTemplate getJmsTemplate() {
		return jmsTemplate;
	}

	public void setJmsTemplate(JmsTemplate jmsTemplate) {
		this.jmsTemplate = jmsTemplate;
	}
	
	public Destination getDestination() {
		return destination;
	}

	public void setDestination(Destination destination) {
		this.destination = destination;
	}

	public boolean receiveEmptyMessage() throws JMSException {
		Message emptyMsg = jmsTemplate.receive(destination);		
		return emptyMsg != null && emptyMsg.getBooleanProperty("isPayloadEmpty");
	}
}

applicationContext.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
		<property name="brokerURL" value="tcp://localhost:61616" />
	</bean>
	<bean id="messageDestination" class="org.apache.activemq.command.ActiveMQQueue">
		<constructor-arg value="messageQueue1" />
	</bean>
	<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
		<property name="connectionFactory" ref="connectionFactory" />
		<property name="receiveTimeout" value="10000" />
	</bean>

	<bean id="jmsProducer" class="com.javacodegeeks.spring.jms.JmsProducer">
		<property name="destination" ref="messageDestination" />
		<property name="jmsTemplate" ref="jmsTemplate" />
	</bean>
	
	<bean id="jmsConsumer" class="com.javacodegeeks.spring.jms.JmsConsumer">
		<property name="destination" ref="messageDestination" />
		<property name="jmsTemplate" ref="jmsTemplate" />
	</bean>

</beans>

EmptyMessageExample:

package com.javacodegeeks.spring.jms;

import java.net.URI;
import java.net.URISyntaxException;

import org.apache.activemq.broker.BrokerFactory;
import org.apache.activemq.broker.BrokerService;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class EmptyMessageExample {
	public static void main(String[] args) throws URISyntaxException, Exception {
		BrokerService broker = BrokerFactory.createBroker(new URI(
				"broker:(tcp://localhost:61616)"));
		broker.start();
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
				"applicationContext.xml");

		try {
			JmsProducer producer = (JmsProducer) context
					.getBean("jmsProducer");
			producer.sendEmptyMessage();

			JmsConsumer consumer = (JmsConsumer) context
					.getBean("jmsConsumer");
			System.out.println("Consumer receives empty message? " + consumer.receiveEmptyMessage());
		} finally {
			broker.stop();
			context.close();
		}
	}
}

Output:

 INFO | JMX consoles can connect to service:jmx:rmi:///jndi/rmi://localhost:1099/jmxrmi
 INFO | PListStore:[C:\javacodegeeks_ws\jmsMessageTypesExample\activemq-data\localhost\tmp_storage] started
 INFO | Using Persistence Adapter: KahaDBPersistenceAdapter[C:\javacodegeeks_ws\jmsMessageTypesExample\activemq-data\localhost\KahaDB]
 INFO | KahaDB is version 6
 INFO | Recovering from the journal @1:6384
 INFO | Recovery replayed 1 operations from the journal in 0.01 seconds.
 INFO | Apache ActiveMQ 5.12.0 (localhost, ID:INMAA1-L1005-54826-1445602271279-0:1) is starting
 INFO | Listening for connections at: tcp://127.0.0.1:61616
 INFO | Connector tcp://127.0.0.1:61616 started
 INFO | Apache ActiveMQ 5.12.0 (localhost, ID:INMAA1-L1005-54826-1445602271279-0:1) started
 INFO | For help or more information please see: http://activemq.apache.org
 WARN | Store limit is 102400 mb (current store usage is 0 mb). The data directory: C:\javacodegeeks_ws\jmsMessageTypesExample\activemq-data\localhost\KahaDB only has 40444 mb of usable space - resetting to maximum available disk space: 40444 mb
 WARN | Temporary Store limit is 51200 mb, whilst the temporary data directory: C:\javacodegeeks_ws\jmsMessageTypesExample\activemq-data\localhost\tmp_storage only has 40444 mb of usable space - resetting to maximum available 40444 mb.
Producer sends empty message
Consumer receives empty message? true
 INFO | Apache ActiveMQ 5.12.0 (localhost, ID:INMAA1-L1005-54826-1445602271279-0:1) is shutting down
 INFO | Connector tcp://127.0.0.1:61616 stopped
 INFO | PListStore:[C:\javacodegeeks_ws\jmsMessageTypesExample\activemq-data\localhost\tmp_storage] stopped
 INFO | Stopping async queue tasks
 INFO | Stopping async topic tasks
 INFO | Stopped KahaDB
 INFO | Apache ActiveMQ 5.12.0 (localhost, ID:INMAA1-L1005-54826-1445602271279-0:1) uptime 1.396 seconds
 INFO | Apache ActiveMQ 5.12.0 (localhost, ID:INMAA1-L1005-54826-1445602271279-0:1) is shutdown

3. TextMessage

The most common type of message is the text message which carries a java.lang.String as its payload. The text message is created using the factory method createTextMessage() on session object.

session.createTextMessage(msg);

When a consumer receives the Message object, we type cast it to TextMessage object and then extract the String payload using the getText() method.

JmsProducer:

package com.javacodegeeks.spring.jms;

import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;

import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;

public class JmsProducer {
	private JmsTemplate jmsTemplate;
	private Destination destination;
	
	public JmsTemplate getJmsTemplate() {
		return jmsTemplate;
	}

	public void setJmsTemplate(JmsTemplate jmsTemplate) {
		this.jmsTemplate = jmsTemplate;
	}
	
	public Destination getDestination() {
		return destination;
	}

	public void setDestination(Destination destination) {
		this.destination = destination;
	}

	public void sendEmptyMessage() {
		System.out.println("Producer sends empty message");
		jmsTemplate.send(destination, new MessageCreator() {
			public Message createMessage(Session session) throws JMSException {
				Message msg = session.createMessage();
				msg.setBooleanProperty("isPayloadEmpty", true);
				return msg;
			}});		
	}
	
	public void sendTextMessage(final String msg) {
		System.out.println("Producer sends " + msg);
		jmsTemplate.send(destination, new MessageCreator() {
			public Message createMessage(Session session) throws JMSException {
				return session.createTextMessage(msg);
			}});		
	}
}

JmsConsumer:

package com.javacodegeeks.spring.jms;

import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.TextMessage;

import org.springframework.jms.core.JmsTemplate;

public class JmsConsumer {
	private JmsTemplate jmsTemplate;
	private Destination destination;
	
	public JmsTemplate getJmsTemplate() {
		return jmsTemplate;
	}

	public void setJmsTemplate(JmsTemplate jmsTemplate) {
		this.jmsTemplate = jmsTemplate;
	}
	
	public Destination getDestination() {
		return destination;
	}

	public void setDestination(Destination destination) {
		this.destination = destination;
	}
	
	public boolean receiveEmptyMessage() throws JMSException {
		Message emptyMsg = jmsTemplate.receive(destination);		
		return emptyMsg != null && emptyMsg.getBooleanProperty("isPayloadEmpty");
	}
	
	public String receiveTextMessage() throws JMSException {
		TextMessage textMessage = (TextMessage) jmsTemplate.receive(destination);		
		return textMessage.getText();
	}
}

TextMessageExample:

package com.javacodegeeks.spring.jms;

import java.net.URI;
import java.net.URISyntaxException;

import org.apache.activemq.broker.BrokerFactory;
import org.apache.activemq.broker.BrokerService;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TextMessageExample {
	public static void main(String[] args) throws URISyntaxException, Exception {
		BrokerService broker = BrokerFactory.createBroker(new URI(
				"broker:(tcp://localhost:61616)"));
		broker.start();
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
				"applicationContext.xml");

		try {
			JmsProducer producer = (JmsProducer) context
					.getBean("jmsProducer");
			producer.sendTextMessage("Hi");

			JmsConsumer consumer = (JmsConsumer) context
					.getBean("jmsConsumer");
			System.out.println("Consumer receives " + consumer.receiveTextMessage());
		} finally {
			broker.stop();
			context.close();
		}
	}
}

Output:

 INFO | PListStore:[C:\javacodegeeks_ws\jmsMessageTypesExample\activemq-data\localhost\tmp_storage] started
 INFO | JMX consoles can connect to service:jmx:rmi:///jndi/rmi://localhost:1099/jmxrmi
 INFO | Using Persistence Adapter: KahaDBPersistenceAdapter[C:\javacodegeeks_ws\jmsMessageTypesExample\activemq-data\localhost\KahaDB]
 INFO | KahaDB is version 6
 INFO | Recovering from the journal @1:10866
 INFO | Recovery replayed 1 operations from the journal in 0.011 seconds.
 INFO | Apache ActiveMQ 5.12.0 (localhost, ID:INMAA1-L1005-56772-1445604024033-0:1) is starting
 INFO | Listening for connections at: tcp://127.0.0.1:61616
 INFO | Connector tcp://127.0.0.1:61616 started
 INFO | Apache ActiveMQ 5.12.0 (localhost, ID:INMAA1-L1005-56772-1445604024033-0:1) started
 INFO | For help or more information please see: http://activemq.apache.org
 WARN | Store limit is 102400 mb (current store usage is 0 mb). The data directory: C:\javacodegeeks_ws\jmsMessageTypesExample\activemq-data\localhost\KahaDB only has 40442 mb of usable space - resetting to maximum available disk space: 40442 mb
 WARN | Temporary Store limit is 51200 mb, whilst the temporary data directory: C:\javacodegeeks_ws\jmsMessageTypesExample\activemq-data\localhost\tmp_storage only has 40442 mb of usable space - resetting to maximum available 40442 mb.
Producer sends Hi
Consumer receives Hi
 INFO | Apache ActiveMQ 5.12.0 (localhost, ID:INMAA1-L1005-56772-1445604024033-0:1) is shutting down
 INFO | Connector tcp://127.0.0.1:61616 stopped
 INFO | PListStore:[C:\javacodegeeks_ws\jmsMessageTypesExample\activemq-data\localhost\tmp_storage] stopped
 INFO | Stopping async queue tasks
 INFO | Stopping async topic tasks
 INFO | Stopped KahaDB
 INFO | Apache ActiveMQ 5.12.0 (localhost, ID:INMAA1-L1005-56772-1445604024033-0:1) uptime 1.404 seconds
 INFO | Apache ActiveMQ 5.12.0 (localhost, ID:INMAA1-L1005-56772-1445604024033-0:1) is shutdown

4. ObjectMessage

If we want to send a serialized POJO object, we can make use of ObjectMessage. For example a person object.

Person:

package com.javacodegeeks.spring.jms;

import java.io.Serializable;

public class Person implements Serializable {
	private static final long serialVersionUID = 1L;
	private String name;
	private Integer age;
	public Person(String name, Integer age) {
		this.name = name;
		this.age = age;
	}
	public String getName() {
		return name;
	}
	public Integer getAge() {
		return age;
	}
	public String toString() {
		return "Person: name(" + name + "), age(" + age + ")";
	}
}

Object messages can be created with the factory method defined in the Session interface createObjectMessage(). In order for this type of message to work, the payload class should be known both to the producer as well as to the consumer. Let’s now send and receive the person object.

JmsProducer:

package com.javacodegeeks.spring.jms;

import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;

import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;

public class JmsProducer {
	private JmsTemplate jmsTemplate;
	private Destination destination;
	
	public JmsTemplate getJmsTemplate() {
		return jmsTemplate;
	}

	public void setJmsTemplate(JmsTemplate jmsTemplate) {
		this.jmsTemplate = jmsTemplate;
	}
	
	public Destination getDestination() {
		return destination;
	}

	public void setDestination(Destination destination) {
		this.destination = destination;
	}

	public void sendEmptyMessage() {
		System.out.println("Producer sends empty message");
		jmsTemplate.send(destination, new MessageCreator() {
			public Message createMessage(Session session) throws JMSException {
				Message msg = session.createMessage();
				msg.setBooleanProperty("isPayloadEmpty", true);
				return msg;
			}});		
	}
	
	public void sendTextMessage(final String msg) {
		System.out.println("Producer sends " + msg);
		jmsTemplate.send(destination, new MessageCreator() {
			public Message createMessage(Session session) throws JMSException {
				return session.createTextMessage(msg);
			}});		
	}
	
	public void sendObjectMessage(final Person person) {
		System.out.println("Producer sends " + person);
		jmsTemplate.send(destination, new MessageCreator() {
			public Message createMessage(Session session) throws JMSException {
				return session.createObjectMessage(person);
			}});		
	}
}

In receiveObjectMessage(), we receive the message, type cast it to ObjectMessage and call message.getObject() to retrieve the encapsulated Person object.

JmsConsumer:

package com.javacodegeeks.spring.jms;

import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.ObjectMessage;
import javax.jms.TextMessage;

import org.springframework.jms.core.JmsTemplate;

public class JmsConsumer {
	private JmsTemplate jmsTemplate;
	private Destination destination;
	
	public JmsTemplate getJmsTemplate() {
		return jmsTemplate;
	}

	public void setJmsTemplate(JmsTemplate jmsTemplate) {
		this.jmsTemplate = jmsTemplate;
	}
	
	public Destination getDestination() {
		return destination;
	}

	public void setDestination(Destination destination) {
		this.destination = destination;
	}
	
	public boolean receiveEmptyMessage() throws JMSException {
		Message emptyMsg = jmsTemplate.receive(destination);		
		return emptyMsg != null && emptyMsg.getBooleanProperty("isPayloadEmpty");
	}
	
	public String receiveTextMessage() throws JMSException {
		TextMessage textMessage = (TextMessage) jmsTemplate.receive(destination);		
		return textMessage.getText();
	}
	
	public Person receiveObjectMessage() throws JMSException {
		ObjectMessage message = (ObjectMessage) jmsTemplate.receive(destination);		
		return (Person) message.getObject();
	}
}

In this example, we create a Person object and producer send it across to the queue which the consumer receives it later.

ObjectMessageExample:

package com.javacodegeeks.spring.jms;

import java.net.URI;
import java.net.URISyntaxException;

import org.apache.activemq.broker.BrokerFactory;
import org.apache.activemq.broker.BrokerService;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class ObjectMessageExample {
	public static void main(String[] args) throws URISyntaxException, Exception {
		BrokerService broker = BrokerFactory.createBroker(new URI(
				"broker:(tcp://localhost:61616)"));
		broker.start();
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
				"applicationContext.xml");

		try {
			JmsProducer producer = (JmsProducer) context
					.getBean("jmsProducer");
			producer.sendObjectMessage(new Person("Joe", 32));

			JmsConsumer consumer = (JmsConsumer) context
					.getBean("jmsConsumer");
			System.out.println("Consumer receives " + consumer.receiveObjectMessage());
		} finally {
			broker.stop();
			context.close();
		}
	}
}

Output:

 INFO | JMX consoles can connect to service:jmx:rmi:///jndi/rmi://localhost:1099/jmxrmi
 INFO | PListStore:[C:\javacodegeeks_ws\jmsMessageTypesExample\activemq-data\localhost\tmp_storage] started
 INFO | Using Persistence Adapter: KahaDBPersistenceAdapter[C:\javacodegeeks_ws\jmsMessageTypesExample\activemq-data\localhost\KahaDB]
 INFO | KahaDB is version 6
 INFO | Recovering from the journal @1:13202
 INFO | Recovery replayed 1 operations from the journal in 0.012 seconds.
 INFO | Apache ActiveMQ 5.12.0 (localhost, ID:INMAA1-L1005-57280-1445604527624-0:1) is starting
 INFO | Listening for connections at: tcp://127.0.0.1:61616
 INFO | Connector tcp://127.0.0.1:61616 started
 INFO | Apache ActiveMQ 5.12.0 (localhost, ID:INMAA1-L1005-57280-1445604527624-0:1) started
 INFO | For help or more information please see: http://activemq.apache.org
 WARN | Store limit is 102400 mb (current store usage is 0 mb). The data directory: C:\javacodegeeks_ws\jmsMessageTypesExample\activemq-data\localhost\KahaDB only has 40444 mb of usable space - resetting to maximum available disk space: 40444 mb
 WARN | Temporary Store limit is 51200 mb, whilst the temporary data directory: C:\javacodegeeks_ws\jmsMessageTypesExample\activemq-data\localhost\tmp_storage only has 40444 mb of usable space - resetting to maximum available 40444 mb.
Producer sends Person: name(Joe), age(32)
Consumer receives Person: name(Joe), age(32)
 INFO | Apache ActiveMQ 5.12.0 (localhost, ID:INMAA1-L1005-57280-1445604527624-0:1) is shutting down
 INFO | Connector tcp://127.0.0.1:61616 stopped
 INFO | PListStore:[C:\javacodegeeks_ws\jmsMessageTypesExample\activemq-data\localhost\tmp_storage] stopped
 INFO | Stopping async queue tasks
 INFO | Stopping async topic tasks
 INFO | Stopped KahaDB
 INFO | Apache ActiveMQ 5.12.0 (localhost, ID:INMAA1-L1005-57280-1445604527624-0:1) uptime 1.415 seconds
 INFO | Apache ActiveMQ 5.12.0 (localhost, ID:INMAA1-L1005-57280-1445604527624-0:1) is shutdown

5. BytesMessage

If we our requirement is a custom payload containing an array of primitive bytes we will use the BytesMessage type. The end result is a stream of “uninterpreted” bytes. BytesMessages are useful when you want to send a message composed of raw data. For example, in order to create a BytesMessage, a client uses the createBytesMessage method on the session. If your payload consists of a string and an int raw data, your payload will be:

BytesMessage bytesMessage = session.createBytesMessage();
bytesMessage.writeUTF(person.getName());
bytesMessage.writeInt(person.getAge());

See sendByteMessage() where we write person object’s members to byte array.

JmsProducer:

package com.javacodegeeks.spring.jms;

import javax.jms.BytesMessage;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;

import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;

public class JmsProducer {
	private JmsTemplate jmsTemplate;
	private Destination destination;
	
	public JmsTemplate getJmsTemplate() {
		return jmsTemplate;
	}

	public void setJmsTemplate(JmsTemplate jmsTemplate) {
		this.jmsTemplate = jmsTemplate;
	}
	
	public Destination getDestination() {
		return destination;
	}

	public void setDestination(Destination destination) {
		this.destination = destination;
	}

	public void sendEmptyMessage() {
		System.out.println("Producer sends empty message");
		jmsTemplate.send(destination, new MessageCreator() {
			public Message createMessage(Session session) throws JMSException {
				Message msg = session.createMessage();
				msg.setBooleanProperty("isPayloadEmpty", true);
				return msg;
			}});		
	}
	
	public void sendTextMessage(final String msg) {
		System.out.println("Producer sends " + msg);
		jmsTemplate.send(destination, new MessageCreator() {
			public Message createMessage(Session session) throws JMSException {
				return session.createTextMessage(msg);
			}});		
	}
	
	public void sendObjectMessage(final Person person) {
		System.out.println("Producer sends " + person);
		jmsTemplate.send(destination, new MessageCreator() {
			public Message createMessage(Session session) throws JMSException {
				return session.createObjectMessage(person);
			}});		
	}

	public void sendByteMessage(final Person person) {
		System.out.println("Producer sends " + person + " using byte message");
		jmsTemplate.send(destination, new MessageCreator() {
			public Message createMessage(Session session) throws JMSException {
				BytesMessage bytesMessage = session.createBytesMessage();
				bytesMessage.writeUTF(person.getName());
				bytesMessage.writeInt(person.getAge());
				return bytesMessage;
			}});
	}
}

In readBytesMessage(), we read the bytes in the order they were written and re-construct the Person object.

JmsConsumer:

package com.javacodegeeks.spring.jms;

import javax.jms.BytesMessage;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.ObjectMessage;
import javax.jms.TextMessage;

import org.springframework.jms.core.JmsTemplate;

public class JmsConsumer {
	private JmsTemplate jmsTemplate;
	private Destination destination;
	
	public JmsTemplate getJmsTemplate() {
		return jmsTemplate;
	}

	public void setJmsTemplate(JmsTemplate jmsTemplate) {
		this.jmsTemplate = jmsTemplate;
	}
	
	public Destination getDestination() {
		return destination;
	}

	public void setDestination(Destination destination) {
		this.destination = destination;
	}
	
	public boolean receiveEmptyMessage() throws JMSException {
		Message emptyMsg = jmsTemplate.receive(destination);		
		return emptyMsg != null && emptyMsg.getBooleanProperty("isPayloadEmpty");
	}
	
	public String receiveTextMessage() throws JMSException {
		TextMessage textMessage = (TextMessage) jmsTemplate.receive(destination);		
		return textMessage.getText();
	}
	
	public Person receiveObjectMessage() throws JMSException {
		ObjectMessage message = (ObjectMessage) jmsTemplate.receive(destination);		
		return (Person) message.getObject();
	}
	
	public Person receiveBytesMessage() throws JMSException {
		BytesMessage message = (BytesMessage) jmsTemplate.receive(destination);		
		Person person = new Person(message.readUTF(), message.readInt());
		return person;
	}
}

ByteMessageExample:

package com.javacodegeeks.spring.jms;

import java.net.URI;
import java.net.URISyntaxException;

import org.apache.activemq.broker.BrokerFactory;
import org.apache.activemq.broker.BrokerService;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class ByteMessageExample {
	public static void main(String[] args) throws URISyntaxException, Exception {
		BrokerService broker = BrokerFactory.createBroker(new URI(
				"broker:(tcp://localhost:61616)"));
		broker.start();
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
				"applicationContext.xml");

		try {
			JmsProducer producer = (JmsProducer) context
					.getBean("jmsProducer");
			producer.sendByteMessage(new Person("Joe", 32));

			JmsConsumer consumer = (JmsConsumer) context
					.getBean("jmsConsumer");
			System.out.println("Consumer receives " + consumer.receiveBytesMessage());
		} finally {
			broker.stop();
			context.close();
		}
	}
}

Output:

 INFO | JMX consoles can connect to service:jmx:rmi:///jndi/rmi://localhost:1099/jmxrmi
 INFO | PListStore:[C:\javacodegeeks_ws\jmsMessageTypesExample\activemq-data\localhost\tmp_storage] started
 INFO | Using Persistence Adapter: KahaDBPersistenceAdapter[C:\javacodegeeks_ws\jmsMessageTypesExample\activemq-data\localhost\KahaDB]
 INFO | KahaDB is version 6
 INFO | Recovering from the journal @1:15860
 INFO | Recovery replayed 1 operations from the journal in 0.012 seconds.
 INFO | Apache ActiveMQ 5.12.0 (localhost, ID:INMAA1-L1005-51494-1445609767726-0:1) is starting
 INFO | Listening for connections at: tcp://127.0.0.1:61616
 INFO | Connector tcp://127.0.0.1:61616 started
 INFO | Apache ActiveMQ 5.12.0 (localhost, ID:INMAA1-L1005-51494-1445609767726-0:1) started
 INFO | For help or more information please see: http://activemq.apache.org
 WARN | Store limit is 102400 mb (current store usage is 0 mb). The data directory: C:\javacodegeeks_ws\jmsMessageTypesExample\activemq-data\localhost\KahaDB only has 40439 mb of usable space - resetting to maximum available disk space: 40439 mb
 WARN | Temporary Store limit is 51200 mb, whilst the temporary data directory: C:\javacodegeeks_ws\jmsMessageTypesExample\activemq-data\localhost\tmp_storage only has 40439 mb of usable space - resetting to maximum available 40439 mb.
Producer sends Person: name(Joe), age(32) using byte message
Consumer receives Person: name(Joe), age(32)
 INFO | Apache ActiveMQ 5.12.0 (localhost, ID:INMAA1-L1005-51494-1445609767726-0:1) is shutting down
 INFO | Connector tcp://127.0.0.1:61616 stopped
 INFO | PListStore:[C:\javacodegeeks_ws\jmsMessageTypesExample\activemq-data\localhost\tmp_storage] stopped
 INFO | Stopping async queue tasks
 INFO | Stopping async topic tasks
 INFO | Stopped KahaDB
 INFO | Apache ActiveMQ 5.12.0 (localhost, ID:INMAA1-L1005-51494-1445609767726-0:1) uptime 1.424 seconds
 INFO | Apache ActiveMQ 5.12.0 (localhost, ID:INMAA1-L1005-51494-1445609767726-0:1) is shutdown

6. StreamMessage

A stream message contains a stream of Java primitive values. A stream message implements the StreamMessage interface defined by JMS.

StreamMessage resembles the BytesMessage, the main difference is StreamMessage keeps track of the order and types of primitives written to the stream.

JmsProducer:

package com.javacodegeeks.spring.jms;

import javax.jms.BytesMessage;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.StreamMessage;

import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;

public class JmsProducer {
	private JmsTemplate jmsTemplate;
	private Destination destination;
	
	public JmsTemplate getJmsTemplate() {
		return jmsTemplate;
	}

	public void setJmsTemplate(JmsTemplate jmsTemplate) {
		this.jmsTemplate = jmsTemplate;
	}
	
	public Destination getDestination() {
		return destination;
	}

	public void setDestination(Destination destination) {
		this.destination = destination;
	}

	public void sendEmptyMessage() {
		System.out.println("Producer sends empty message");
		jmsTemplate.send(destination, new MessageCreator() {
			public Message createMessage(Session session) throws JMSException {
				Message msg = session.createMessage();
				msg.setBooleanProperty("isPayloadEmpty", true);
				return msg;
			}});		
	}
	
	public void sendTextMessage(final String msg) {
		System.out.println("Producer sends " + msg);
		jmsTemplate.send(destination, new MessageCreator() {
			public Message createMessage(Session session) throws JMSException {
				return session.createTextMessage(msg);
			}});		
	}
	
	public void sendObjectMessage(final Person person) {
		System.out.println("Producer sends " + person);
		jmsTemplate.send(destination, new MessageCreator() {
			public Message createMessage(Session session) throws JMSException {
				return session.createObjectMessage(person);
			}});		
	}

	public void sendByteMessage(final Person person) {
		System.out.println("Producer sends " + person + " using byte message");
		jmsTemplate.send(destination, new MessageCreator() {
			public Message createMessage(Session session) throws JMSException {
				BytesMessage bytesMessage = session.createBytesMessage();
				bytesMessage.writeUTF(person.getName());
				bytesMessage.writeInt(person.getAge());
				return bytesMessage;
			}});
	}
	
	public void sendStreamMessage(final Person person) {
		System.out.println("Producer sends " + person + " using stream message");
		jmsTemplate.send(destination, new MessageCreator() {
			public Message createMessage(Session session) throws JMSException {
				StreamMessage streamMessage = session.createStreamMessage();
				streamMessage.writeString(person.getName());
				streamMessage.writeInt(person.getAge());
				return streamMessage;
			}});
	}	
}

JmsConsumer:

package com.javacodegeeks.spring.jms;

import javax.jms.BytesMessage;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.ObjectMessage;
import javax.jms.StreamMessage;
import javax.jms.TextMessage;

import org.springframework.jms.core.JmsTemplate;

public class JmsConsumer {
	private JmsTemplate jmsTemplate;
	private Destination destination;
	
	public JmsTemplate getJmsTemplate() {
		return jmsTemplate;
	}

	public void setJmsTemplate(JmsTemplate jmsTemplate) {
		this.jmsTemplate = jmsTemplate;
	}
	
	public Destination getDestination() {
		return destination;
	}

	public void setDestination(Destination destination) {
		this.destination = destination;
	}
	
	public boolean receiveEmptyMessage() throws JMSException {
		Message emptyMsg = jmsTemplate.receive(destination);		
		return emptyMsg != null && emptyMsg.getBooleanProperty("isPayloadEmpty");
	}
	
	public String receiveTextMessage() throws JMSException {
		TextMessage textMessage = (TextMessage) jmsTemplate.receive(destination);		
		return textMessage.getText();
	}
	
	public Person receiveObjectMessage() throws JMSException {
		ObjectMessage message = (ObjectMessage) jmsTemplate.receive(destination);		
		return (Person) message.getObject();
	}
	
	public Person receiveBytesMessage() throws JMSException {
		BytesMessage message = (BytesMessage) jmsTemplate.receive(destination);		
		Person person = new Person(message.readUTF(), message.readInt());
		return person;
	}
	
	public Person receiveStreamMessage() throws JMSException {
		StreamMessage message = (StreamMessage) jmsTemplate.receive(destination);		
		Person person = new Person(message.readString(), message.readInt());
		return person;
	}
}

StreamMessageExample:

package com.javacodegeeks.spring.jms;

import java.net.URI;
import java.net.URISyntaxException;

import org.apache.activemq.broker.BrokerFactory;
import org.apache.activemq.broker.BrokerService;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class StreamMessageExample {
	public static void main(String[] args) throws URISyntaxException, Exception {
		BrokerService broker = BrokerFactory.createBroker(new URI(
				"broker:(tcp://localhost:61616)"));
		broker.start();
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
				"applicationContext.xml");

		try {
			JmsProducer producer = (JmsProducer) context
					.getBean("jmsProducer");
			producer.sendStreamMessage(new Person("Joe", 32));

			JmsConsumer consumer = (JmsConsumer) context
					.getBean("jmsConsumer");
			System.out.println("Consumer receives " + consumer.receiveStreamMessage());
		} finally {
			broker.stop();
			context.close();
		}
	}
}

Output:

 INFO | PListStore:[C:\javacodegeeks_ws\jmsMessageTypesExample\activemq-data\localhost\tmp_storage] started
 INFO | JMX consoles can connect to service:jmx:rmi:///jndi/rmi://localhost:1099/jmxrmi
 INFO | Using Persistence Adapter: KahaDBPersistenceAdapter[C:\javacodegeeks_ws\jmsMessageTypesExample\activemq-data\localhost\KahaDB]
 INFO | KahaDB is version 6
 INFO | Recovering from the journal @1:20372
 INFO | Recovery replayed 18 operations from the journal in 0.011 seconds.
 INFO | Apache ActiveMQ 5.12.0 (localhost, ID:INMAA1-L1005-54302-1445612288792-0:1) is starting
 INFO | Listening for connections at: tcp://127.0.0.1:61616
 INFO | Connector tcp://127.0.0.1:61616 started
 INFO | Apache ActiveMQ 5.12.0 (localhost, ID:INMAA1-L1005-54302-1445612288792-0:1) started
 INFO | For help or more information please see: http://activemq.apache.org
 WARN | Store limit is 102400 mb (current store usage is 0 mb). The data directory: C:\javacodegeeks_ws\jmsMessageTypesExample\activemq-data\localhost\KahaDB only has 40197 mb of usable space - resetting to maximum available disk space: 40197 mb
 WARN | Temporary Store limit is 51200 mb, whilst the temporary data directory: C:\javacodegeeks_ws\jmsMessageTypesExample\activemq-data\localhost\tmp_storage only has 40197 mb of usable space - resetting to maximum available 40197 mb.
Producer sends Person: name(Joe), age(32) using stream message
Consumer receives Person: name(Joe), age(32)
 INFO | Apache ActiveMQ 5.12.0 (localhost, ID:INMAA1-L1005-54302-1445612288792-0:1) is shutting down
 INFO | Connector tcp://127.0.0.1:61616 stopped
 INFO | PListStore:[C:\javacodegeeks_ws\jmsMessageTypesExample\activemq-data\localhost\tmp_storage] stopped
 INFO | Stopping async queue tasks
 INFO | Stopping async topic tasks
 INFO | Stopped KahaDB
 INFO | Apache ActiveMQ 5.12.0 (localhost, ID:INMAA1-L1005-54302-1445612288792-0:1) uptime 1.590 seconds
 INFO | Apache ActiveMQ 5.12.0 (localhost, ID:INMAA1-L1005-54302-1445612288792-0:1) is shutdown

7. MapMessage

This type of message is similar to a HashMap, it contains key-value pairs as its payload. The values can be Java primitives (or their wrappers) in addition to Strings. A MapMessage class is useful if is one is not sure about the keys and the keyed data may change from one message to the next. We don’t have to worry about the order of the internal pieces.

JmsProducer:

package com.javacodegeeks.spring.jms;

import javax.jms.BytesMessage;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.StreamMessage;

import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;

public class JmsProducer {
	private JmsTemplate jmsTemplate;
	private Destination destination;
	
	public JmsTemplate getJmsTemplate() {
		return jmsTemplate;
	}

	public void setJmsTemplate(JmsTemplate jmsTemplate) {
		this.jmsTemplate = jmsTemplate;
	}
	
	public Destination getDestination() {
		return destination;
	}

	public void setDestination(Destination destination) {
		this.destination = destination;
	}

	public void sendEmptyMessage() {
		System.out.println("Producer sends empty message");
		jmsTemplate.send(destination, new MessageCreator() {
			public Message createMessage(Session session) throws JMSException {
				Message msg = session.createMessage();
				msg.setBooleanProperty("isPayloadEmpty", true);
				return msg;
			}});		
	}
	
	public void sendTextMessage(final String msg) {
		System.out.println("Producer sends " + msg);
		jmsTemplate.send(destination, new MessageCreator() {
			public Message createMessage(Session session) throws JMSException {
				return session.createTextMessage(msg);
			}});		
	}
	
	public void sendObjectMessage(final Person person) {
		System.out.println("Producer sends " + person);
		jmsTemplate.send(destination, new MessageCreator() {
			public Message createMessage(Session session) throws JMSException {
				return session.createObjectMessage(person);
			}});		
	}

	public void sendByteMessage(final Person person) {
		System.out.println("Producer sends " + person + " using byte message");
		jmsTemplate.send(destination, new MessageCreator() {
			public Message createMessage(Session session) throws JMSException {
				BytesMessage bytesMessage = session.createBytesMessage();
				bytesMessage.writeUTF(person.getName());
				bytesMessage.writeInt(person.getAge());
				return bytesMessage;
			}});
	}
	
	public void sendStreamMessage(final Person person) {
		System.out.println("Producer sends " + person + " using stream message");
		jmsTemplate.send(destination, new MessageCreator() {
			public Message createMessage(Session session) throws JMSException {
				StreamMessage streamMessage = session.createStreamMessage();
				streamMessage.writeString(person.getName());
				streamMessage.writeInt(person.getAge());
				return streamMessage;
			}});
	}	
	
	public void sendMapMessage(final Person person) {
		System.out.println("Producer sends " + person + " using map message");
		jmsTemplate.send(destination, new MessageCreator() {
			public Message createMessage(Session session) throws JMSException {
				MapMessage mapMessage = session.createMapMessage();
				mapMessage.setString("name", person.getName());
				mapMessage.setInt("age", person.getAge());
				return mapMessage;
			}});
	}	
}

The values written to the MapMessage can then be read by a JMS consumer using the name as a key:

JmsConsumer:

package com.javacodegeeks.spring.jms;

import javax.jms.BytesMessage;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.ObjectMessage;
import javax.jms.StreamMessage;
import javax.jms.TextMessage;

import org.springframework.jms.core.JmsTemplate;

public class JmsConsumer {
	private JmsTemplate jmsTemplate;
	private Destination destination;
	
	public JmsTemplate getJmsTemplate() {
		return jmsTemplate;
	}

	public void setJmsTemplate(JmsTemplate jmsTemplate) {
		this.jmsTemplate = jmsTemplate;
	}
	
	public Destination getDestination() {
		return destination;
	}

	public void setDestination(Destination destination) {
		this.destination = destination;
	}
	
	public boolean receiveEmptyMessage() throws JMSException {
		Message emptyMsg = jmsTemplate.receive(destination);		
		return emptyMsg != null && emptyMsg.getBooleanProperty("isPayloadEmpty");
	}
	
	public String receiveTextMessage() throws JMSException {
		TextMessage textMessage = (TextMessage) jmsTemplate.receive(destination);		
		return textMessage.getText();
	}
	
	public Person receiveObjectMessage() throws JMSException {
		ObjectMessage message = (ObjectMessage) jmsTemplate.receive(destination);		
		return (Person) message.getObject();
	}
	
	public Person receiveBytesMessage() throws JMSException {
		BytesMessage message = (BytesMessage) jmsTemplate.receive(destination);		
		Person person = new Person(message.readUTF(), message.readInt());
		return person;
	}
	
	public Person receiveStreamMessage() throws JMSException {
		StreamMessage message = (StreamMessage) jmsTemplate.receive(destination);		
		Person person = new Person(message.readString(), message.readInt());
		return person;
	}
	
	public Person receiveMapMessage() throws JMSException {
		MapMessage message = (MapMessage) jmsTemplate.receive(destination);		
		Person person = new Person(message.getString("name"), message.getInt("age"));
		return person;
	}
}

MapMessageExample:

package com.javacodegeeks.spring.jms;

import java.net.URI;
import java.net.URISyntaxException;

import org.apache.activemq.broker.BrokerFactory;
import org.apache.activemq.broker.BrokerService;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MapMessageExample {
	public static void main(String[] args) throws URISyntaxException, Exception {
		BrokerService broker = BrokerFactory.createBroker(new URI(
				"broker:(tcp://localhost:61616)"));
		broker.start();
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
				"applicationContext.xml");

		try {
			JmsProducer producer = (JmsProducer) context
					.getBean("jmsProducer");
			producer.sendMapMessage(new Person("Joe", 32));

			JmsConsumer consumer = (JmsConsumer) context
					.getBean("jmsConsumer");
			System.out.println("Consumer receives " + consumer.receiveMapMessage());
		} finally {
			broker.stop();
			context.close();
		}
	}
}

Output:

 INFO | JMX consoles can connect to service:jmx:rmi:///jndi/rmi://localhost:1099/jmxrmi
 INFO | PListStore:[C:\javacodegeeks_ws\jmsMessageTypesExample\activemq-data\localhost\tmp_storage] started
 INFO | Using Persistence Adapter: KahaDBPersistenceAdapter[C:\javacodegeeks_ws\jmsMessageTypesExample\activemq-data\localhost\KahaDB]
 INFO | KahaDB is version 6
 INFO | Recovering from the journal @1:27393
 INFO | Recovery replayed 1 operations from the journal in 0.012 seconds.
 INFO | Apache ActiveMQ 5.12.0 (localhost, ID:INMAA1-L1005-54793-1445612694641-0:1) is starting
 INFO | Listening for connections at: tcp://127.0.0.1:61616
 INFO | Connector tcp://127.0.0.1:61616 started
 INFO | Apache ActiveMQ 5.12.0 (localhost, ID:INMAA1-L1005-54793-1445612694641-0:1) started
 INFO | For help or more information please see: http://activemq.apache.org
 WARN | Store limit is 102400 mb (current store usage is 0 mb). The data directory: C:\javacodegeeks_ws\jmsMessageTypesExample\activemq-data\localhost\KahaDB only has 40194 mb of usable space - resetting to maximum available disk space: 40194 mb
 WARN | Temporary Store limit is 51200 mb, whilst the temporary data directory: C:\javacodegeeks_ws\jmsMessageTypesExample\activemq-data\localhost\tmp_storage only has 40194 mb of usable space - resetting to maximum available 40194 mb.
Producer sends Person: name(Joe), age(32) using map message
Consumer receives Person: name(Joe), age(32)
 INFO | Apache ActiveMQ 5.12.0 (localhost, ID:INMAA1-L1005-54793-1445612694641-0:1) is shutting down
 INFO | Connector tcp://127.0.0.1:61616 stopped
 INFO | PListStore:[C:\javacodegeeks_ws\jmsMessageTypesExample\activemq-data\localhost\tmp_storage] stopped
 INFO | Stopping async queue tasks
 INFO | Stopping async topic tasks
 INFO | Stopped KahaDB
 INFO | Apache ActiveMQ 5.12.0 (localhost, ID:INMAA1-L1005-54793-1445612694641-0:1) uptime 1.460 seconds
 INFO | Apache ActiveMQ 5.12.0 (localhost, ID:INMAA1-L1005-54793-1445612694641-0:1) is shutdown

8. Download the Eclipse Project

This was an example of JMS Message Types.

Download
You can download the full source code of this example here: jmsMessageTypesExample.zip

Ram Mokkapaty

Ram holds a master's degree in Machine Design from IT B.H.U. His expertise lies in test driven development and re-factoring. He is passionate about open source technologies and actively blogs on various java and open-source technologies like spring. He works as a principal Engineer in the logistics domain.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button