【发布时间】:2021-06-24 05:40:34
【问题描述】:
我创建了一个小演示来展示 RabbitMQ 基础知识。不幸的是,它没有按预期工作,有两个问题。我正在使用 .NET Core 3.1 和 RabbitMQ.Client 6.2.2
我创建了从任务队列接收消息的 Employee 类。第一个员工工作得很好,但如果我让更多员工开始工作,他们就不会工作(不接收消息)。我不知道为什么会这样。
如果我在队列中有很多消息(在开始第二个员工之前),我会看到任务队列中的所有消息在第二个开始时都得到确认,然后在很短的时间后它们再次变为未确认。有点奇怪。
但主要是:为什么其他员工不工作?
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Text;
using System.Threading;
namespace DemoTasks.Employee
{
class Employee
{
static void Main(string[] args)
{
string clientName = "Employee-" + Guid.NewGuid().ToString();
Console.Title = clientName;
Console.WriteLine("Moin moin");
IConnectionFactory connectionFactory = new ConnectionFactory
{
HostName = "localhost",
Port = 5672,
VirtualHost = "/",
UserName = "user",
Password = "password",
ClientProvidedName = clientName
};
using (IConnection connection = connectionFactory.CreateConnection(clientName))
{
using (IModel model = connection.CreateModel())
{
model.ExchangeDeclare("jobs", "fanout", false, false, null);
model.QueueDeclare("tasks", true, false, false);
model.QueueBind("tasks", "jobs", "", null);
EventingBasicConsumer consumer = new EventingBasicConsumer(model);
consumer.Received += OnWorkReceived;
model.BasicConsume("tasks", false, clientName + ":OnWorkReceived", consumer);
Console.ReadLine();
model.Close();
}
connection.Close();
}
Console.WriteLine("Wochenende ... woooh !!!");
}
private static void OnWorkReceived(object sender, BasicDeliverEventArgs e)
{
EventingBasicConsumer consumer = (EventingBasicConsumer)sender;
IModel model = consumer.Model;
string task = Encoding.UTF8.GetString(e.Body.ToArray());
Console.Write("working on: " + task + " ... ");
Thread.Sleep(5000);
Console.WriteLine("done!");
model.BasicAck(e.DeliveryTag, false);
}
}
}
【问题讨论】:
-
参见stackoverflow.com/questions/10620976/… 或stackoverflow.com/questions/42351130/… - 无论是问题还是答案都可能会给您一些启发。说出您希望第二名员工的行为可能会有所帮助 - 所有员工都处理相同的消息还是他们共享/循环