Search code examples
javaspring-bootibm-mqspring-jms

Spring Boot MQ listener enable always


I have Spring boot application which reads the message from IBM QUEUE. I want my Listener queue to keep listening for new message in Queue but I see it reads the message once then stop listening. below is the code is that anything I am missing here?

@SpringBootApplication
@EnableJms
public class Application implements CommandLineRunner {

    @Autowired
    private JmsTemplate jmsTemplate;

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
        System.out.println("******done!!!");
    }


    @Override
    public void run(String... args) throws Exception {
        try {
            System.out.println("jmsTemplate:  " + jmsTemplate);
            final Message message =  jmsTemplate.receive("MYQUEUE");
            String msgBody = ((TextMessage) message).getText();
            System.out.println("message RECEIVED :    " + message);

        } catch (Exception ex) {
            ex.printStackTrace();

        }

        
    }
 
}

Solution

  • In order to consume multiple messages, you'd need to call jmsTemplate.receive() multiple times. Perhaps in a loop?

    But I'd recommend making use of @JmsListener so that you don't even have to worry about writing your own polling mechanism.

    Here is a tutorial on @JmsListener. You really just need to supply a JmsListenerContainerFactory bean, and annotate a method with @JmsListener, and that method will be invoked every time the queue you subscribe to receives a message.

      @Bean
      public JmsListenerContainerFactory<?> myFactory(ConnectionFactory connectionFactory,
                              DefaultJmsListenerContainerFactoryConfigurer configurer) {
        DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
        configurer.configure(factory, connectionFactory);
        return factory;
      }
    
      @JmsListener(destination = "mailbox", containerFactory = "myFactory")
      public void receiveMessage(Email email) {
        System.out.println("Received <" + email + ">");
      }