How can I pull messages from Activemq Asynchronously

天大地大妈咪最大 提交于 2019-12-03 17:34:43

If you are using a MessageListener, then you are actually receiving messages asynchronously (in another thread).

You are probably looking for synchronous message reception, so try this in your main thread:

final QueueReceiver queueReceiver = queueSession.createReceiver(queue);
queueConnection.start();

while (true) {
  Message message = queueReceiver.receive();
  // Process your message: insert the code from MyListener.onMessage here

  // Possibly add an explit message.acknowledge() here, 
  // if you want to make sure that in case of an exception no message is lost
  // (requires Session.CLIENT_ACKNOWLEDGE, when you create the queue session)

  // Possibly terminate program, if a certain condition/situation arises
}

without a MessageListener.

receive() blocks until a message is available, so your main thread (and thus your program) waits in the receive method. If a message arrives, it will receive and process it.

Update

If you use

Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);

then you should call

message.acknowledge()

after the message has been processed completely.

Whereas in case of Session.AUTO_ACKNOWLEDGE the message is removed from the queue immediately (and is therefore lost, if the program terminates whilte processing the message).

jan

Instead of using a MessageListener you could use the receive() method in the MessageConsumer object. This way you only get one message each time you call the receive() method.

MessageConsumer consumer = session.createConsumer(destination); 
Message message = consumer.receive(1000);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!