Add JMS MessageListener to MessageConsumer - Java Message

Java examples for Message:JMS

Description

Add JMS MessageListener to 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 VirtualTopidConsumer_1 {

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

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

    try {
      connectionFactory = new ActiveMQConnectionFactory(
          "failover:(nio://10.10.16.164:61617,tcp://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("Consumer.A.VirtualTopic.UserReg");
      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