2014-04-06 127 views
0

我的JMS消費者在白天在JMS隊列上產生任意數量的消息(說n)。首先,我正在評估消息的同步處理:在23.0時鐘處說,現在我想消費所有消息。以下是主要方法順序/同時處理jms消息?

這裏是如何做到這一點順序(不兼): -

我需要調用consumer.receive()方法n次(直到返回consumer.receive()返回NULL)對單一消費者?

  ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost"); 
      // Create a Connection 
      Connection connection = connectionFactory.createConnection(); 
      connection.start(); 

      // Create a Session 
      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); 

      // Create the destination (Topic or Queue) 
      Destination destination = session.createQueue("TEST.FOO"); 

      // Create a MessageConsumer from the Session to the Topic or Queue 
      MessageConsumer consumer = session.createConsumer(destination); 

      // Wait for a message 
      Message message = consumer.receive(); 

如何做到這一點的同時: - 我要處理的20條消息同時

我需要創建20線程,每個線程創建自己的消費和接收消息?

+0

你有沒有嘗試過自己的建議? – SimonC

+0

@Simon第一個我試過但關於第二個我不確定是否是正確的方法? – user3198603

回答

0

要按順序處理20條消息,並且您知道至少會收到20條消息,請將該呼叫置於循環中20次。請注意,如果隊列中沒有消息,沒有超時參數的MessageConsumer.receive()將不會返回null。它會阻塞直到它收到一條消息,或者直到調用close()。如果使用MessageConsumer.receive(longTimeoutValue),它將等待longTimeoutValue接收消息,如果沒有收到消息,則返回null。

對於併發消息處理,ActiveMQ文檔提供瞭如何在這裏使用多個使用者的示例:http://activemq.apache.org/hello-world.html,您可以根據自己的目的修改該示例。該示例爲每個線程創建一個新連接,但根據http://activemq.apache.org/multiple-consumers-on-a-queue.html,您只需要爲每個線程創建一個會話和使用者。

+0

@Ireeder正如我在帖子中所說的,「每個線程都創建自己的消費者」並非單一的消費者。所以看起來我不是正確的道路? – user3198603

+0

每個線程都應該創建自己的消費者,但它也應該爲每個消費者創建一個單獨的會話。 – lreeder

+0

@Ireeder那是正確的 – user3198603