Search code examples
javajbossjmshornetq

Paginating JMS Queue


In my Java EE application I use JMS to store some messages. I want to display these messages in a JSF paginated table. How can I get the messages from the queue in batches? For the moment I'm using something like this, but it's not very nice because I need to loop through many messages.

Can this be achieved? I'm using JBoss with HornetQ.

browser = session.createBrowser(queue);
List<Message> messagesToReturn = new ArrayList<>();
final Enumeration<ObjectMessage> messages = browser.getEnumeration();
int messagesSoFar = 0;
int count = 0;

while(messages.hasMoreElements()) {
    ObjectMessage message = messages.nextElement();
    if (count >= offset) {
        messagesToReturn.add(new CGSQueueMessage(message));
        messagesSoFar += 1;
    }
    if (messagesSoFar == maxSelect) {
        break;
    }
    count += 1;
}
return messagesToReturn;

Solution

  • There are no methods in the JMS API to get messages from the queue in batches for a paginated use-case like yours.

    You could read all the messages from the queue browser into your own data structure and paginate using that.

    If there were too many messages to fit them all into an in-memory data structure at once then you could read as many of them as you could reasonably fit into memory (which presumably will be more than what the user sees on any given page) and that would serve as your own kind of application-level page which you could use for serving up the user-level pages. That would reduced the number of times you need to loop through the queue browser.

    Aside from that you could dump all the messages from the queue browser into a temporary, random-access file and pull the results from that.

    All that said, I think your use-case doesn't ultimately fit with a messaging API like JMS. In my view I think you'd be better suited using something like a database which could easily support this use-case.