implements JMS MessageListener - Java Message

Java examples for Message:JMS

Description

implements JMS MessageListener

Demo Code



import java.util.Date;

import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;

public class Client implements MessageListener
{
  private MessageProducer producer;

  public Client()
  {/*from w w w  . ja  va  2s . c  o m*/
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("admin", "admin", "tcp://172.16.0.191:61616");

    Connection connection;
    try
    {
      connection = connectionFactory.createConnection();
      connection.start();
      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      Destination destination = session.createQueue("com.balitimes.QueueReply");
      this.producer = session.createProducer(destination);
      this.producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
      TextMessage txtMessage = session.createTextMessage();
      txtMessage.setText("send by Client");

      Destination tmpDestination = session.createTemporaryQueue();
      MessageConsumer consumer = session.createConsumer(tmpDestination);
      consumer.setMessageListener(this); 
      txtMessage.setJMSReplyTo(tmpDestination);
      String correlationId = new Date().toString();
      txtMessage.setJMSCorrelationID(correlationId);
      System.out.println("correlationId is " + correlationId);
      
      this.producer.send(txtMessage);
    }
    catch (JMSException e)
    {
      // TODO: handle exception
    }
  }

  public void onMessage(Message message)
  {
    try
    {
      if (message instanceof TextMessage)
      {
        TextMessage txtMessage = (TextMessage) message;
        System.out.println("Message Text = " + txtMessage.getText());
      }
    }
    catch (JMSException e)
    {
      // TODO: handle exception
    }

  }

  public static void main(String[] args)
  {


    new Client();

  }

}

Related Tutorials