Search code examples
c#activemq-classicnms

ActiveMQ Queue Count Stops at 400


I am creating an application to connect to multiple ActiveMQ servers and get the total number of messages withing their different queues.

I am using a slightly modified version of the code found in this link ActiveMQ with C# and Apache NMS - Count messages in queue to count the messages withing the queue.

The problem I am having is that if the queue contains more than 400 messages this code stops counting at 400.

public static int GetMessageCount(string server, string user, string pw) {

        int messageCount = 0;
        var _server = $"activemq:ssl://{server}:61616?transport.acceptInvalidBrokerCert=true";

        IConnectionFactory factory = new NMSConnectionFactory(_server);

        using (IConnection connection = factory.CreateConnection(user, pw)) {
            connection.Start();
            using (ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge)) {
                IDestination requestDestination = session.GetQueue(QueueRequestUri);

                IQueueBrowser queueBrowser = session.CreateBrowser((IQueue)requestDestination);
                IEnumerator messages = queueBrowser.GetEnumerator();

                while (messages.MoveNext()) {
                    IMessage message = (IMessage)messages.Current;
                    messageCount++;
                }

                connection.Close();
                session.Close();
                connection.Close();
            }
        }

        return messageCount;
    }

How do I get the actual number of messages in the queue?

Why is this behavior? Is this an issue with IEnumerator interface or is it an issue with the Apache.NMS.ActiveMQ API?


Solution

  • Normally there is no guarantee that the browser will return all messages from the queue. It provides a snapshot of the messages but may not return all of them. ActiveMQ has a limit for overhead reduction. You can increase the limits, see maxBrowsePageSize, however there is still no guarantee.

    maxBrowsePageSize - 400 - The maximum number of messages to page in from the store at one time for a browser.

    Those APIs are not designed for counting messages and you shouldn't do it. Just process the messages without counting them. If you want to get metrics then use some kind of admin libraries. JMX (yes I know you use C#) could be helpful as well.