使用 C# 和 Apache NMS 的 ActiveMQ - 对队列中的消息进行计数
我正在使用 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++;
}
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++;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我现在没有 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 :