我正在使用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
,这不是我所知道的最佳实践
答案 0 :(得分:4)
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();
}