问题
The MessageListener interface only defines a method onMessage that receives a single Message as argument. I'm looking for a way to get multiple Messages from a queue so that I can process the batch and then acknowledge all the Messages in the batch.
Is there such feature in JMS world? If no, is it supported by ActiveMQ as an extension?
Thanks, Mickael
回答1:
This is explained in JMS 1.1 spec section 4.5.1 Synchronous Delivery:
A client can request the next message from a MessageConsumer using one of its receive methods. There are several variations of receive that allow a client to poll or wait for the next message.
There is even a code example in Section 9.2.2 Receiving a Message Synchronously:
TextMessage stockMessage;
stockMessage = (TextMessage)receiver.receive();
Note that you should also have a look into acknowledgement when using polling and batch processing - see section 4.4.11 Message Acknowledgment for further information on this. Especially interesting could be the following:
CLIENT_ACKNOWLEDGE - With this option, a client acknowledges a message by calling the message’s acknowledge method. Acknowledging a consumed message automatically acknowledges the receipt of all messages that have been delivered by its session.
回答2:
Yes this is part of the regular JMS API. Instead of doing your consumption in a MessageListener do it in a loop using MessageConsumer.receive(). For it to be transactionally batched, you need to use the SESSION_TRANSACTED acknowledgement mode, and call Session.commit() when you want to send the batch acknowledgement.
Take a look at the source code for the sjms-batch component in Apache Camel to see how this is done.
来源:https://stackoverflow.com/questions/35742002/batch-consuming-of-jms-messages