如何实现JMS异步消息接收器

时间:2014-12-12 09:23:46

标签: java jms

为了接收Jboss JMS的消息,我编写了JMS异步消息接收器

见下面的代码

public class QueueReceive implements MessageListener
{

 public final static String JNDI_FACTORY="org.jnp.interfaces.NamingContextFactory";


 public final static String JMS_FACTORY="ConnectionFactory";

 public final static String QUEUE="/queue/requestQueue";

 private QueueConnectionFactory qconFactory;
 private QueueConnection qcon;
 private QueueSession qsession;
 private QueueReceiver qreceiver;
 private Queue queue;
 private boolean quit = false;

 public void onMessage(Message msg)
 {
    try {
        System.out.println("onMessage");
     String msgText;
     if (msg instanceof TextMessage) {
       msgText = ((TextMessage)msg).getText();
     } else {
       msgText = msg.toString();
     }

     System.out.println("Message Received: "+ msgText );

     if (msgText.equalsIgnoreCase("quit")) {
       synchronized(this) {
         quit = true;
         this.notifyAll(); // Notify main thread to quit
       }
     }
    } catch (JMSException jmse) {
     System.err.println("An exception occurred: "+jmse.getMessage());
    }
 }


 public void init(Context ctx, String queueName)
    throws NamingException, JMSException
 {
    qconFactory = (QueueConnectionFactory) ctx.lookup(JMS_FACTORY);
    qcon = qconFactory.createQueueConnection();
    qsession = qcon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
    queue = (Queue) ctx.lookup(queueName);
    qreceiver = qsession.createReceiver(queue);
    qreceiver.setMessageListener(this);
    qcon.start();



 }

 public void close()throws JMSException
 {
    qreceiver.close();
    qsession.close();
    qcon.close();
 }


 public static void main(String[] args) throws Exception {

    InitialContext ic = getInitialContext("jnp://host:port");
    QueueReceive qr = new QueueReceive();
    System.out.println("Ready to initialize");
    qr.init(ic, QUEUE);

    System.out.println("JMS Ready To Receive Messages (To quit, send a \"quit\" message).");
   // qr.onMessage(qr.qreceiver.receive());
    System.out.println("Message Receivd");
    // Wait until a "quit" message has been received.
    synchronized(qr) {
     while (!qr.quit) {
       try {
         qr.wait();
       } catch (InterruptedException ie) {}
     }
    }
    qr.close();
 }

 private static InitialContext getInitialContext(String url)
    throws NamingException
 {
    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY);
    env.put(Context.PROVIDER_URL, url);
    return new InitialContext(env);
 }
}

当我运行java程序时,它不会直接调用onMessage方法,请帮我如何收到JMS消息。

从这段代码我可以ping JMS messenger并且无法读取消息吗?

0 个答案:

没有答案