Spring - Using a MessageListener to receive messages and JmsTemplate to send messages

[Updated: Sep 8, 2017, Created: Sep 5, 2017]

This example demonstrates the use of JmsTemplate to send JMS messages and a javax.jms.MessageListener implementation for asynchronously receiving the messages. In the example, the MessageListener will be driven by Spring's message listener container. The message listener container allows us to register MessageListeners without EJB container.

Example

A MessageListener

package com.logicbig.example;

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

public class MyJmsListener implements MessageListener {
  @Override
  public void onMessage(Message message) {
      if (message instanceof TextMessage) {
          try {
              String text = ((TextMessage) message).getText();
              System.out.println("received: " + text);
          } catch (JMSException e) {
              e.printStackTrace();
          }
      }
  }
}

Using JmsTemplate to send messages

@Component
public class MyMessageSender {

  @Autowired
  private ConnectionFactory connectionFactory;
  private JmsTemplate jmsTemplate;

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

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

Java config and main class

@Configuration
@ComponentScan
public class AppConfig {
  public static final String QUEUE_NAME = "example.queue";

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

  @Bean
  public MessageListenerContainer listenerContainer() {
      DefaultMessageListenerContainer container = new DefaultMessageListenerContainer();
      container.setConnectionFactory(connectionFactory());
      container.setDestinationName(QUEUE_NAME);
      container.setMessageListener(new MyJmsListener());
      return container;
  }

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

      MyMessageSender ms = context.getBean(MyMessageSender.class);
      ms.sendMessage("test message 1");
      ms.sendMessage("test message 2");

      System.out.println("-- shutting down listener container --");
      DefaultMessageListenerContainer container = context.getBean(DefaultMessageListenerContainer.class);
      container.shutdown();
  }
}

Output

INFO | Using Persistence Adapter: KahaDBPersistenceAdapter[D:\LogicBig\example-projects\spring-jms\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:\LogicBig\example-projects\spring-jms\activemq-data\localhost\tmp_storage] started
 INFO | Apache ActiveMQ 5.15.0 (localhost, ID:xxxx) is starting
 INFO | Apache ActiveMQ 5.15.0 (localhost, ID:xxx) 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:\LogicBig\example-projects\spring-jms\activemq-data\localhost\KahaDB only has 52658 mb of usable space. - resetting to maximum available disk space: 52658 mb
 INFO | Connector vm://localhost started
sending: test message 1
received: test message 1
sending: test message 2
received: test message 2
-- shutting down listener container --
 INFO | Connector vm://localhost stopped
 INFO | Apache ActiveMQ 5.15.0 (localhost, ID:xxx) is shutting down
 INFO | PListStore:[D:\LogicBig\example-projects\spring-jms\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:xxx) uptime 1.868 seconds
 INFO | Apache ActiveMQ 5.15.0 (localhost, ID:xxx) is shutdown

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 with MessageListener Example Select All Download
  • jms-template-with-jms-listener
    • src
      • main
        • java
          • com
            • logicbig
              • example

See Also