How to find a horneq Queue length

skyde picture skyde · Feb 2, 2011 · Viewed 8k times · Source

I am using Hornetq 2.0 i dont understand how can i know how many message are sitting on the queue at the moment.

This is a very useful feature so i can know at runtime if my consumer consume message fast enough.

I am not using the JMS api but the highly optimised core API.

What is the right (fastest) way to get the number of message in the queue ?

I found 2 way but don't know what is the proper way to do it.

public int size(){

    ClientSession session;

    try {

        session = sf.createSession(false, false, false);

        ClientRequestor requestor = new ClientRequestor(session, "hornetq.management");

        ClientMessage m = session.createMessage(false);

        ManagementHelper.putAttribute(m, "core.queue." + queueName, "messageCount");

        ClientMessage reply = requestor.request(m);

        int count = (Integer) ManagementHelper.getResult(reply);

        return count;

    } catch (Exception e) {

        e.printStackTrace();

    }

    return 0;

}

or

public synchronized int size(){

    ClientSession coreSession = null;

    int count = 0;

    try {

        coreSession = sf.createSession(false, false, false);

        ClientSession.QueueQuery result;

        result = coreSession.queueQuery(new SimpleString(queueName));

        count = result.getMessageCount();

    } catch (HornetQException e) {

        e.printStackTrace();

    } finally {

        if (coreSession!= null ){

            try {

                coreSession.close();

            } catch (HornetQException e) {

                e.printStackTrace();

            }

        }

    }

    return count;

}

Answer

skyde picture skyde · Feb 11, 2011

I found those 2 ways

public synchronized int size(){
    ClientSession session;
    try {
        session = sf.createSession(false, false, false);
        ClientRequestor requestor = new ClientRequestor(session, "hornetq.management");
        ClientMessage m = session.createMessage(false);
        ManagementHelper.putAttribute(m, "core.queue." + queueName, "messageCount");
        ClientMessage reply = requestor.request(m);
        int count = (Integer) ManagementHelper.getResult(reply);
        return count;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return 0;
}

and

public synchronized int size(){
    ClientSession coreSession = null;
    int count = 0;
    try {
        coreSession = sf.createSession(false, false, false);
        ClientSession.QueueQuery result;
        result = coreSession.queueQuery(new SimpleString(queueName));
        count = result.getMessageCount();
    } catch (HornetQException e) {
        e.printStackTrace();
    } finally {
        if (coreSession!= null ){
            try {
                coreSession.close();
            } catch (HornetQException e) {
                e.printStackTrace();
            }
        }
    }
    return count;
}