The basic RabbitMQ tutorial给出了如何从队列中连续检索消息的示例:
var factory = new ConnectionFactory() { HostName = "localhost" };
using (var connection = factory.CreateConnection())
{
using (var channel = connection.CreateModel())
{
channel.QueueDeclare("hello", false, false, false, null);
var consumer = new QueueingBasicConsumer(channel);
channel.BasicConsume("hello", true, consumer);
Console.WriteLine(" [*] Waiting for messages." +
"To exit press CTRL+C");
while (true)
{
var ea = (BasicDeliverEventArgs)consumer.Queue.Dequeue();
var body = ea.Body;
var message = Encoding.UTF8.GetString(body);
Console.WriteLine(" [x] Received {0}", message);
}
}
}
我想要做的是检索已放入队列然后停止的所有消息。
以下是两个可以解决我的问题的例子
OR
我意识到我可能会在我的消息中加上一个时间戳并检查它,或者我可以设置超时值,但我想知道是否有任何内置方法来正确执行此操作。
提前致谢。
答案 0 :(得分:6)
从评论看来,RabbitMQ似乎不适合批量处理,因此它不是为此而设计的。
我还注意到,在测试DequeueNoWait方法或尝试以零超时出列时,它们根本不起作用,只是返回null。
以下解决方案使用QueueDeclare来获取现有消息的计数,并且不需要时间戳或hacky超时:
var factory = new ConnectionFactory { HostName = "localhost" };
using (var connection = factory.CreateConnection())
{
using (var channel = connection.CreateModel())
{
var queueDeclareResponse = channel.QueueDeclare(Constants.QueueName, false, false, false, null);
var consumer = new QueueingBasicConsumer(channel);
channel.BasicConsume(Constants.QueueName, true, consumer);
Console.WriteLine(" [*] Processing existing messages.");
for (int i = 0; i < queueDeclareResponse.MessageCount; i++)
{
var ea = (BasicDeliverEventArgs)consumer.Queue.Dequeue();
var body = ea.Body;
var message = Encoding.UTF8.GetString(body);
Console.WriteLine(" [x] Received {0}", message);
}
Console.WriteLine("Finished processing {0} messages.", queueDeclareResponse.MessageCount);
Console.ReadLine();
}
}
答案 1 :(得分:1)