Create JMS MessageConsumer - Java Message

Java examples for Message:JMS

Description

Create JMS MessageConsumer

Demo Code


import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Consumer {

  private static Logger logger = LoggerFactory.getLogger(Consumer.class);

  public static void main(String[] args) {
    ActiveMQConnectionFactory connectionFactory = null;
    QueueConnection connection = null;/*from w ww.j  av a 2 s . com*/

    try {
      connectionFactory = new ActiveMQConnectionFactory("failover:(nio://10.10.16.164:61617,nio://10.10.16.164:31617)?randomize=false");
      connection = connectionFactory.createQueueConnection();
      connection.start();
      final Session session = connection.createQueueSession(true, Session.AUTO_ACKNOWLEDGE);
      Queue destination = session.createQueue("activemq.test.queue");
      MessageConsumer consumer = session.createConsumer(destination);
      MessageListener listener = new MessageListener() {
        @Override
        public void onMessage(Message message) {
          TextMessage textMessage = (TextMessage) message;
          try {
            logger.info("consumer --->>>> {}", textMessage.getText());
            session.commit();
          } catch (JMSException e) {
            e.printStackTrace();
          }
        }
      }
      consumer.setMessageListener(listener);

      while (true) {
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        connection.close();
      } catch (JMSException e) {
        e.printStackTrace();
      }
    }
  }

}

Related Tutorials