我一直在做一个小示例应用程序来使用 RabbitMQ 中队列上的消息。
代码应该读取消息并调用 REST API(此处替换为Task.Delay):
static void Main(string[] args)
{
var factory = new ConnectionFactory
{
Uri = new Uri("..."),
DispatchConsumersAsync = true
};
var connection = factory.CreateConnection();
var channel = connection.CreateModel();
var consumer = new AsyncEventingBasicConsumer(channel);
consumer.Received += async (model, eventArgs) =>
{
Console.WriteLine("Doing a fake API call...");
await Task.Delay(2000);
Console.WriteLine("Done with fake API call!");
channel.BasicAck(eventArgs.DeliveryTag, false);
};
channel.BasicConsume("myQueue", false, consumer);
}
Run Code Online (Sandbox Code Playgroud)
当我使用队列中的 5 条消息运行此应用程序时,我得到以下结果:

消息被一一处理,2 秒的延迟大约需要 10 秒。我本来希望看到五行,Doing a fake API call...然后是五行,Done …
rabbitmq ×1