Close

Spring - Sending and Receiving messages with JmsTemplate

[Updated: Aug 30, 2017, Created: Aug 30, 2017]

The JmsTemplate class is the central class for Spring JMS integration. It simplifies the use of JMS.

By default, JmsTemplate uses Point-to-Point (Queues) and the JMS Sessions are "not transacted" and "auto-acknowledge".

In the following example, we will use Apache ActiveMQ as the provider implementation of JMS. We are going to send and synchronously receive JMS messages.

Example

Maven dependencies

pom.xml

<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-jms</artifactId>
   <version>4.3.10.RELEASE</version>
</dependency>
<dependency>
   <groupId>org.apache.activemq</groupId>
   <artifactId>activemq-all</artifactId>
   <version>5.15.0</version>
</dependency>

Using JmsTemplate

package com.logicbig.example;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;

@Component
public class MyMessageSender {

  @Autowired
  private ConnectionFactory connectionFactory;
  private JmsTemplate jmsTemplate;

  @PostConstruct
  public void init() {
      this.jmsTemplate = new JmsTemplate(connectionFactory);
  }

  public void sendMessage(String queueName, String message) {
      System.out.println("sending: " + message);
      jmsTemplate.send(queueName, new MessageCreator() {
          @Override
          public Message createMessage(Session session) throws JMSException {
              return session.createTextMessage(message);
          }
      });
  }
}
package com.logicbig.example;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.TextMessage;

@Component
public class MyMessageReceiver {

  @Autowired
  private ConnectionFactory connectionFactory;
  private JmsTemplate jmsTemplate;

  @PostConstruct
  public void init() {
      this.jmsTemplate = new JmsTemplate(connectionFactory);
  }

  public void receiveMessage(String queueName) {
      Message message = jmsTemplate.receive(queueName);
      TextMessage textMessage = (TextMessage) message;
      try {
          String text = textMessage.getText();
          System.out.println("received: " + text);
      } catch (JMSException e) {
          e.printStackTrace();
      }
  }
}

Java config and main class

package com.logicbig.example;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import javax.jms.ConnectionFactory;

@Configuration
@ComponentScan
public class AppConfig {

  @Bean
  public ConnectionFactory connectionFactory() {
      ConnectionFactory connectionFactory =
              new ActiveMQConnectionFactory("vm://localhost");
      return connectionFactory;
  }

  public static void main(String[] args) throws InterruptedException {
      AnnotationConfigApplicationContext context =
              new AnnotationConfigApplicationContext(AppConfig.class);

      String queueName = "example.queue";
      MyMessageSender ms = context.getBean(MyMessageSender.class);
      ms.sendMessage(queueName, "test message");

      MyMessageReceiver mr = context.getBean(MyMessageReceiver.class);
      mr.receiveMessage(queueName);
  }
}

Output

sending: test message
 INFO | Using Persistence Adapter: KahaDBPersistenceAdapter[D:\example-projects\spring-jms\jms-template-example\activemq-data\localhost\KahaDB]
 INFO | JMX consoles can connect to service:jmx:rmi:///jndi/rmi://localhost:1099/jmxrmi
 INFO | PListStore:[D:\example-projects\spring-jms\jms-template-example\activemq-data\localhost\tmp_storage] started
 INFO | Apache ActiveMQ 5.15.0 (localhost, ID:xxxx-58548-1504149855063-0:1) is starting
 INFO | Apache ActiveMQ 5.15.0 (localhost, ID:xxxx-58548-1504149855063-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: D:\example-projects\spring-jms\jms-template-example\activemq-data\localhost\KahaDB only has 53036 mb of usable space. - resetting to maximum available disk space: 53036 mb
 INFO | Connector vm://localhost started
 INFO | Connector vm://localhost stopped
 INFO | Apache ActiveMQ 5.15.0 (localhost, ID:xxxx-58548-1504149855063-0:1) is shutting down
 INFO | PListStore:[D:\example-projects\spring-jms\jms-template-example\activemq-data\localhost\tmp_storage] stopped
 INFO | Stopping async queue tasks
 INFO | Stopping async topic tasks
 INFO | Stopped KahaDB
 INFO | Apache ActiveMQ 5.15.0 (localhost, ID:xxxx-58548-1504149855063-0:1) uptime 1.180 seconds
 INFO | Apache ActiveMQ 5.15.0 (localhost, ID:xxxx-58548-1504149855063-0:1) is shutdown
 INFO | Using Persistence Adapter: KahaDBPersistenceAdapter[D:\example-projects\spring-jms\jms-template-example\activemq-data\localhost\KahaDB]
 INFO | JMX consoles can connect to service:jmx:rmi:///jndi/rmi://localhost:1099/jmxrmi
 INFO | KahaDB is version 6
 INFO | PListStore:[D:\example-projects\spring-jms\jms-template-example\activemq-data\localhost\tmp_storage] started
 INFO | Apache ActiveMQ 5.15.0 (localhost, ID:xxxx-58548-1504149855063-0:2) is starting
 INFO | Apache ActiveMQ 5.15.0 (localhost, ID:xxxx-58548-1504149855063-0:2) 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: D:\example-projects\spring-jms\jms-template-example\activemq-data\localhost\KahaDB only has 53036 mb of usable space. - resetting to maximum available disk space: 53036 mb
 INFO | Connector vm://localhost started
 INFO | Connector vm://localhost stopped
 INFO | Apache ActiveMQ 5.15.0 (localhost, ID:xxxx-58548-1504149855063-0:2) is shutting down
 INFO | PListStore:[D:\example-projects\spring-jms\jms-template-example\activemq-data\localhost\tmp_storage] stopped
 INFO | Stopping async queue tasks
 INFO | Stopping async topic tasks
 INFO | Stopped KahaDB
 INFO | Apache ActiveMQ 5.15.0 (localhost, ID:xxxx-58548-1504149855063-0:2) uptime 0.297 seconds
 INFO | Apache ActiveMQ 5.15.0 (localhost, ID:xxxx-58548-1504149855063-0:2) is shutdown
received: test message

Example Project

Dependencies and Technologies Used:

  • spring-context 4.3.10.RELEASE: Spring Context.
  • spring-jms 4.3.10.RELEASE: Spring JMS.
  • activemq-all 5.15.0: Puts together an ActiveMQ jar bundle.
  • JDK 1.8
  • Maven 3.3.9

Spring JmsTemplate Example Select All Download
  • jms-template-example
    • src
      • main
        • java
          • com
            • logicbig
              • example

See Also