Java JMS MessageConsumer handle message event

Description

Java JMS MessageConsumer handle message event

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;

public class Main {
   public static void main(String[] args) {
      try {/*w w  w  .java 2  s . co m*/
         Context ctx = new InitialContext();
         ConnectionFactory cf = (ConnectionFactory) ctx.lookup(args[0]);
         Connection con = cf.createConnection();
         Session sn = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
         Destination dest = sn.createQueue(args[0]);
         MessageConsumer mc = sn.createConsumer(dest);
         con.start();
         mc.setMessageListener(new AListener());
         System.out.println("Continuing its own work");
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}

class AListener implements MessageListener {
   public void onMessage(Message msg) {
      TextMessage tm = (TextMessage) msg;
      try {
         System.out.println("Received: " + tm.getText());
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}



PreviousNext

Related