I want to consume all messages from MQ.
public static void main(String[] args)
{
JMSContext context = null;
Destination destination = null;
JMSConsumer consumer = null;
JmsFactoryFactory FF = JmsFactoryFactory.getInstance(WMQConstants.WMQ_PROVIDER);
JmsConnectionFactor CF = FF.createConnectionFactory();
context = CF.createContext();
destination = context.createQueue(QUEUE_NAME);
consumer = context.createConsumer(destination);
String msg = consumer.receiveBody(String.class, 15090);
System.out.println(msg);
}
It is able to read one message only. How can I consume all messages? Also, is there any simpler way to delete all messages in queue without even reading or consuming them?
The JMS API consumes a single message at a time so you'll need to put your receiveBody
in a loop, e.g.:
public static void main(String[] args) {
JMSContext context = null;
Destination destination = null;
JMSConsumer consumer = null;
JmsFactoryFactory FF = JmsFactoryFactory.getInstance(WMQConstants.WMQ_PROVIDER);
JmsConnectionFactor CF = FF.createConnectionFactory();
context = CF.createContext();
destination = context.createQueue(QUEUE_NAME);
consumer = context.createConsumer(destination);
String msg = null;
do {
msg = consumer.receiveBody(String.class, 15090);
System.out.println(msg);
} while (msg != null);
}
When receiveBody
returns null
that means there's no more messages in the queue.
The JMS API doesn't define any way to delete all the messages from a queue, but most JMS servers have an implementation-specific management API through which you can perform those sorts of actions.