c# - 使用 C# 和 Apache NMS 的 ActiveMQ - 对队列中的消息进行计数

标签 c# message-queue activemq apache-nms

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

    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从这个页面,但也许我应该采取另一种方式来做到这一点?

更新:

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

新的 while 循环是:

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

最佳答案

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

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

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

}

关于c# - 使用 C# 和 Apache NMS 的 ActiveMQ - 对队列中的消息进行计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7512004/

相关文章:

c# - JSON 数组作为空值发送到 Controller

c# - 使用 SQLite 测试 ASP Net Core 应用程序抛出未知函数 : newid()

java - 定期从 MySQL 获取数据

c# - 创建辅助磁贴时出现操作无效错误

c# - C# 和 PhP 中::运算符的含义

c# - 实现分布式队列

c# - 队列的并行处理

java - 将消息存储到变量 RabbitMQ Java

java - ActiveMQ:队列(具有并发消费者)和主题的正确配置

grails - ActiveMQ 嵌入式代理 SSL