我有这个方法消耗来自rabbitMq队列的消息
public void ConsumeMessage(string queueName, IMessagingHandler messageHandler)
{
if (messageHandler == null)
throw new NullReferenceException($"{nameof(messageHandler)} can not be null");
var connection = _factory.CreateConnection();
var channel = connection.CreateModel();
var consumer = new EventingBasicConsumer(channel);
//consumer.Received+= ConsumerOnReceived;
consumer.Received +=async (model, ea) =>
{
_logger.Info($"Message received");
var message = string.Empty;
try
{
if (ea.Body == null)
{
_logger.Error("Null Message Body");
//TODO this should throw a red flag notification error
return;
}
var body = ea.Body;
message = Encoding.UTF8.GetString(body);
var packet = JsonConvert.DeserializeObject<MessagingPackage>(message);
_logger.Info($"Message decoded {message}");
await messageHandler.HandleMessage(packet);
_logger.Info($"Message passed to handler {messageHandler}");
}
catch (Exception ex)
{
_logger.Error(ex.Message,ex);
throw;
}
};
channel.BasicConsume(
queue: queueName,
autoAck: true,
consumer: consumer);
}
注意有一个IMessagingHandler messageHandler
,它作为参数传递给方法。
我遇到的问题是,当执行consumer.Received +=async (model, ea)
事件时,变量messageHandler
为空。
我采用这种方法是因为我希望消费者具有通用性,同时能够为队列中出现的消息实现任何自定义处理程序,因为它是第三方集成的一部分。
所以我的问题是有一种方法可以确保在事件被触发时messageHandler
变量不为null吗?