带有C#和Apache NMS的ActiveMQ-对队列中的消息进行计数 [英] ActiveMQ with C# and Apache NMS - Count messages in queue

查看:699
本文介绍了带有C#和Apache NMS的ActiveMQ-对队列中的消息进行计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ActiveMQ通过C#应用发送和接收消息.但是我在获取队列中的邮件数时遇到了一些困难.这是我的代码:

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;
    }

我以为可以使用QueueBrowser来获取计数,但是它返回的IEnumerator始终为空.我想到了使用 QueueBrowser 的想法,但是也许还有另一种方式我应该这样做?

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?

更新:

我通过枚举器发现的无限循环"问题的解决方案是通过访问当前消息来解决的.现在,它只循环一次(这是正确的,因为队列中只有一条消息).

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).

新的while循环为:

New while loop is:

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

推荐答案

我现在没有ActiveMq,所以我无法尝试 但我认为问题是您没有启动连接.尝试这样:

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...
     }

}

这篇关于带有C#和Apache NMS的ActiveMQ-对队列中的消息进行计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆