ActiveMQ with C# and Apache NMS - Count messages in queue

笑着哭i 提交于 2019-11-27 07:21:02

问题


I'm using ActiveMQ to send and receive messages using a C# app. However I'm having some difficulty just getting a count of the messages in the queue.. Here's my code:

    public int GetMessageCount()
    {
        int messageCount = 0;
        Uri connecturi = new Uri(this.ActiveMQUri);

        IConnectionFactory factory = new NMSConnectionFactory(connecturi);

        using (IConnection connection = factory.CreateConnection())
        using (ISession session = connection.CreateSession())
        {
            IDestination requestDestination = SessionUtil.GetDestination(session, this.QueueRequestUri);

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

            while(messages.MoveNext())
            {
                messageCount++;
            }

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

        return messageCount;
    }

I thought I could use the QueueBrowser to get the count, but the IEnumerator it returns is always empty. I got the idea of using QueueBrowser from this page, but maybe there is another way I should be doing this?

Update:

The solution to the 'infinite loop' issue I found when going through the enumerator was solved by accessing the current message. It now only goes through the loop once (which is correct as there is only one message in the queue).

New while loop is:

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

回答1:


I don't have an ActiveMq with me right now so I can not try it but I think the problem is you are not starting the connection. Try like this :

using (IConnection connection = factory.CreateConnection())
{
    connection.start ();

     using (ISession session = connection.CreateSession())
     {
      //Whatever...
     }

}


来源:https://stackoverflow.com/questions/7512004/activemq-with-c-sharp-and-apache-nms-count-messages-in-queue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!