I have a code that hangs a reader on a queue and receives a message when the method completes. I want to receive messages not from the beginning of the queue but from the end or from the middle
private void getMessage() throws JMSException, NamingException {
Queue queue = (Queue) initialContext.lookup("dynamicQueues/" + "TestQueue");
if (messageConsumer == null){
messageConsumer = queueSession.createConsumer(queue);
}
TextMessage message = (TextMessage) messageConsumer.receive();
String msgBody = ((TextMessage) message).getText();
System.out.println(msgBody);
}
The fundamental semantics of a JMS queue is first-in-first-out (i.e. FIFO). In other words, the broker must dispatch messages to consumers in the order in which they were added to the queue. However, there are two basic ways to get around this.
A JMS message can have a priority from 0 to 9. The priority is set by the producer who sent the message. Messages with a higher priority may be dispatched by the broker to consumers before messages with a lower priority.
A JMS consumer can specify a message selector. Only messages that match the selector will be dispatched to the consumer. These messages will be dispatched in FIFO order relative to each other, but they may jump ahead of other messages that would otherwise be dispatched before them. Selectors only work on the headers or properties of the message so the consumer must know something about the message(s) it wants to consume.
For example, if a producer sends 100 messages and each message has a property myProperty
whose value is 1 to 100 in order and the consumer wants to consume the last message on the queue then it would use the selector myProperty = 100
.
Selector syntax is based on a subset of the SQL92 conditional expression syntax. You can find more information about selectors and how they work in the API docs.