gpt4 book ai didi

c# - RabbitMq 以异步方式处理接收到的消息

转载 作者:太空宇宙 更新时间:2023-11-03 20:55:38 24 4
gpt4 key购买 nike

我正在使用 RabbitMq 来处理我在公交车上收到的消息。我想知道是否有更好的方法来处理我收到的消息(可能使用 async/await 模式)

这是我的代码片段

connection = connectionFactory.CreateConnection();

channel = connection.CreateModel();

channel.QueueDeclare(queue: Constants.RabbitListeningQueue,durable: false,exclusive: false,autoDelete: false,arguments: null);
channel.QueueDeclare(queue: Constants.RabbitMqRequestInsertedQueue,durable: false,exclusive: false,autoDelete: false,arguments: null);

var consumer = new EventingBasicConsumer(channel);
consumer.Received += (model, ea) =>
{
log.Debug($"[x] Received message :{ea}");
var body = ea.Body;
var message = Encoding.UTF8.GetString(body);

var dynamicObject = JObject.Parse(message);

queueMessageHandler.HandleMessage(dynamicObject);
};

queueMessageHandler实现如下

public class QueueMessageHandler : IQueueMessageHandler
{
private readonly IImportNucleoManager importNucleoManager;

public QueueMessageHandler(IImportNucleoManager importNucleoManager)
{
this.importNucleoManager = importNucleoManager;
}

public void HandleMessage(dynamic message)
{
switch ((string)message.Type)
{
case "T1":
{
importNucleoManager.Process(message);
break;
}
case "T3":
importNucleoManager.ProceedToInsertStep(message);
break;
}
}
}

我想知道(因为 T1/T3 事件需要很长时间来处理)它们是否应该是 Task,所以即使是 HandleMessage 也应该是 HandleMessageAsync?在这种情况下,我还必须传递 async void,据我所知,这不是最佳做法

最佳答案

static async Task Main(string[] args)
{
var connectionFactory = new ConnectionFactory(DispatchConsumersAsync = true);
var connection = connectionFactory.CreateConnection();
var channel = connection.CreateModel();

var consumer = new AsyncEventingBasicConsumer(channel);
consumer.Received += Consumer_Received;
}

static async Task Consumer_Received(object sender, BasicDeliverEventArgs @event)
{
await DoSomethingAsync();
}

关于c# - RabbitMq 以异步方式处理接收到的消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50836811/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com