Search code examples
javaspring-bootibm-mq

How to receive messages from IBM MQ JMS using spring boot continuously?


I have spring boot application which receive JSON requests and push it into IBM MQ JMS queue. There can be n number of JSON requests will be pushed to the queue. My Goal is to process each request from the queue. How can i listen to the queue and get the messages one by one to process using spring boot ?


Solution

  • You need to implement listener as:

    1: Create configure following:

    @Bean
    public MQConnectionFactory mqConnectionFactory(){
      MQConnectionFactory connectionFactory = new MQConnectionFactory();
      connectionFactory.setHostName(); //mq host name
      connectionFactory.setPort(); // mq port
      connectionFactory.setQueueManager(); //mq queue manager
      connectionFactory.setChannel(); //mq channel name
      connectionFactory.setTransportType(1);
      connectionFactory.setSSLCipherSuite(); //tls cipher suite name
      return connectionFactory;
    }
    
    
    @Bean()
    public DefaultMessageListenerContainer myMessageEventContainer() {
      DefaultMessageListenerContainer container = new DefaultMessageListenerContainer();
      container.setAutoStartup(true);
      container.setConnectionFactory(mqConnectionFactory);
      container.setDestinationName(//queue name//);
      container.setMessageListener(new MyEventListener());
      return container;
    }
    

    2: Implement message listener:

    public class MyEventListener implements MessageListener {
    
      @Override
      public void onMessage(Message message) {
        try {
          if (message instanceof TextMessage) {
            TextMessage textMessage = (TextMessage) message;
            String stringMessage = textMessage.getText();
            //do something with your message from queue
          }
        } catch (JMSException e) {
          //catch error
        }
      }
    }