WEB开发网
开发学院软件开发Java JMS - 异步消息的使者 阅读

JMS - 异步消息的使者

 2009-09-23 00:00:00 来源:WEB开发网   
核心提示: Receiver:Contextcontext=newInitialContext();QueueConnectionFactoryqueueConnectionFactory=(QueueConnectionFactory)context.lookup("QueueConnectio

Receiver:

       Context context = new InitialContext();
       QueueConnectionFactory queueConnectionFactory = (QueueConnectionFactory) context.lookup("QueueConnectionFactoryTest");
       QueueConnection queueConnection = queueConnectionFactory.createQueueConnection();
       QueueSession queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
       Queue queue = (Queue) context.lookup("QueueTest");
       QueueReceiver queueReceiver = queueSession.createReceiver(queue);
       queueConnection.start();
       while (true) {
            Message m = queueReceiver.receive();
            if (m instanceof TextMessage) {
                TextMessage message = (TextMessage) m;
                System.out.println("Reading message: " + message.getText());
            } else {
                break;
            }
       }
       queueConnection.close();

由上代码可以看出,sender和receiver的实现基本是相同的,下面我们再来对比一下pub/sub模式的实现,

publisher:

      Context context = new InitialContext();
      TopicConnectionFactory topicConnectionFactory = (TopicConnectionFactory) context.lookup("TopicConnectionFactoryTest");
      TopicConnection topicConnection = topicConnectionFactory.createTopicConnection();
      TopicSession topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
      Topic topic = (Topic) context.lookup("TopicTest"); 
      TopicPublisher topicPublisher = topicSession.createPublisher(topic);
      TextMessage sentMessage = topicSession.createTextMessage();
      sentMessage.setText("Here is a message" + i);
      System.out.println("PUBLISHER THREAD: Publishing message: " + sentMessage.getText());
      topicPublisher.publish(sentMessage);
      topicConnection.close();

Tags:JMS 异步 消息

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接