Java JMS MessageConsumer receive message

Description

Java JMS MessageConsumer receive message

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.MessageConsumer;
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 ww .j a  v a  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.createTopic("ATopic");

         MessageConsumer mc = sn.createConsumer(dest);
         con.start();
         TextMessage msg = (TextMessage) mc.receive();
         System.out.println("Received message: " + msg.getText());
         sn.close();
         con.close();
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}



PreviousNext

Related