我有两个针对activeMQ侦听器的代码。我期待案例2更快但不是......
案例1:这里我在main函数中创建了多个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:这里我在多个线程中创建多个activemq监听器
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.");
}
}
}
这是我正在使用的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是否应该更快,因为它在三个不同的线程上运行?
答案 0 :(得分:3)
实际上,您使用3个不同的连接/会话来创建3个MessageListener,因此您在案例1和案例2中同时使用消息。这就是您看到相同吞吐量的原因。
您不需要创建要从队列中并发使用的线程。对于每个会话,您都有一个主题。在以下网址中,他们解释了这一点:
http://activemq.apache.org/multiple-consumers-on-a-queue.html
因此,如果您在案例1中从同一会话创建消息侦听器,并在案例2中从不同会话创建消息侦听器,则应该看到不同。
答案 1 :(得分:2)
MessageListener onMessage是从创建Consumer的Session内部的调度线程的上下文中调用的。由于实际调用onMessage调用的线程始终相同,因此创建的线程数并不重要。在你的情况下,额外的线程将不会为你做任何真正的工作,因为消息继续来自相同的三个连接/会话实例,所以你有三个会话线程在任何一种情况下调度相同的消息。