我正在使用 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/