我们按照以下示例(http://masstransit-project.com/MassTransit/usage/azure-functions.html)尝试使用MassTransit(对于.Net CORE 2.1,Azure Functions 2.0)将Azure Functions设置为Azure Service Bus事件(主题)订阅者。
使用Azure Webjobs时,就像使用RabbitMQ一样简单,配置发布者,让订阅者配置和设置其队列,让Masstransit为每个事件自动创建一个主题,在所有重试后重定向到队列和“ queue_error”失败了。您不必手动设置任何内容。
但是使用Azure Functions,我们似乎必须手动(通过Service Bus Explorer或ARM模板)将订阅者添加到主题(由发布者在其发布的第一个事件上创建)以及队列(尽管这些订阅者甚至没有必要,这些事件由使用中的Azure Function主题订阅者直接处理。)
也许我们做错了,从文档中我看不到MT不会像通常那样设置使用Azure Functions时设置订阅者并创建队列。但这是可行的,除了使用者何时引发异常以及在执行所有安装重试之后。我们只是不会在死信队列中获取该事件,并且通常不会生成MT生成的错误队列。
那么我们如何让MT创建错误队列,并在其中移动失败的事件?
我们的代码:
[FunctionName("OrderShippedConsumer")]
public static Task OrderShippedConsumer(
[ServiceBusTrigger("xyz.events.order/iordershipped", "ordershippedconsumer-queue", Connection = "AzureServiceBus")] Message message,
IBinder binder,
ILogger logger,
CancellationToken cancellationToken,
ExecutionContext context)
{
var config = CreateConfig(context);
var handler = Bus.Factory.CreateBrokeredMessageReceiver(binder, cfg =>
{
var serviceBusEndpoint = Parse.ConnectionString(config["AzureServiceBus"])["Endpoint"];
cfg.CancellationToken = cancellationToken;
cfg.SetLog(logger);
cfg.InputAddress = new Uri($"{serviceBusEndpoint}{QueueName}");
cfg.UseRetry(x => x.Intervals(TimeSpan.FromSeconds(5)));
cfg.Consumer(() => new OrderShippedConsumer(cfg.Log, config));
});
return handler.Handle(message);
}
以及消费者代码:
public OrderShippedConsumer(ILog log, IConfigurationRoot config)
{
this.config = config;
this.log = log;
}
public async Task Consume(ConsumeContext<IOrderShipped> context)
{
// Handle the event
}
}