2014-03-25 27 views
0

我對activeMQ偵聽器有以下兩種情況的代碼。我期待的情況下2要快,但它不是...在單獨的線程或同一線程中創建ActiveMQ偵聽器的差異

案例1:我在這裏的主要功能創建的ActiveMQ多個監聽

public class FileReceiver { 


    public static void main(String[] args) { 
     List<MessageReceiver> messageReceiverList = new ArrayList<MessageReceiver>(); 

     MessageReceiver msgReceiver1 = new MessageReceiver(); 
     messageReceiverList.add(msgReceiver1); 
     msgReceiver1.run(); 

     MessageReceiver msgReceiver2 = new MessageReceiver(); 
     messageReceiverList.add(msgReceiver2); 
     msgReceiver2.run(); 

     MessageReceiver msgReceiver3 = new MessageReceiver(); 
     messageReceiverList.add(msgReceiver3); 
     msgReceiver3.run(); 

    } 
} 

案例2:我在這裏在多線程

public class FileReceiver { 


    public static void main(String[] args) { 
     List<MessageReceiver> messageReceiverList = new ArrayList<MessageReceiver>(); 


     for(int i = 0 ; i < 3 ; i++) { 
      MessageReceiver msgReceiver = new MessageReceiver(); 
      Thread thread = new Thread(msgReceiver); 
      thread.start(); 
      messageReceiverList.add(msgReceiver); 
      System.out.println("Listener " + i + " started."); 
     } 

    } 
} 

這裏創造的ActiveMQ多個監聽器是MessageReceiver類我使用...

class MessageReceiver implements Runnable,MessageListener { 

    private int numMsgsReceived = 0; 

    private void start() { 
     try { 
      ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
        "tcp://localhost:61616"); 
      Connection connection = connectionFactory.createConnection(); 
      connection.start(); 
      ActiveMQSession session = (ActiveMQSession) connection 
        .createSession(false, Session.AUTO_ACKNOWLEDGE); 
      Destination ftQueue = session.createQueue("TEMP.DEST"); 
      MessageConsumer consumer = session.createConsumer(ftQueue); 
      consumer.setMessageListener(this); 

     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 

    public void onMessage(Message msg) { 
     incNumMsgsReceived(); 
     try { 
      Thread.sleep(100); 
     } catch (InterruptedException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 

    public void run() { 
     start(); 

    } 
} 

在這兩種情況下,我每秒只能收到30封郵件。 情況2不應該更快,因爲它在三個獨立的線程上運行?

回答

2

MessageListener onMessage是從創建消費者的Session內部的調度線程的上下文中調用的。它創建的線程數並不重要,因爲實際調用onMessage調用的線程始終是相同的。在你的情況下,額外的線程將不會爲你做任何實際的工作,因爲消息繼續來自相同的三個連接/會話實例,所以無論哪種情況你都有三個會話線程分派相同的消息。

2

實際上,您正在使用3個不同的連接/會話來創建3個MessageListeners,因此您同時在消息1和2中使用消息。這就是您看到相同吞吐量的原因。

您不需要創建線程同時從隊列中使用。對於每個會話你都有一個線程。在下面的網址,他們解釋這一點:

http://activemq.apache.org/multiple-consumers-on-a-queue.html

所以,你應該看到一個區別,如果你從同一個會話的情況下,1創建消息監聽器,並從不同的會話的情況下,2