在 Azure 服务总线中,我需要同时监听来自不同服务总线的多个订阅的消息。
为此,我创建了一个列表,其中包含带有连接字符串、主题、订阅名称和其他一些信息的对象(该列表称为“作业”)。
对于此列表中的每个项目,我将创建一个不同的任务来创建 ServiceBusClient 和处理器。
var jobs = GetAllServiceBusTopics();
Parallel.ForEach(jobs, async job =>
{
var client = new ServiceBusClient(job.Environment.ServiceBusConnectionString);
var options = new ServiceBusProcessorOptions();
var processor = client.CreateProcessor(job.Environment.TopicName, _subscriptionName, new ServiceBusProcessorOptions());
try
{
processor.ProcessMessageAsync += MessageHandler;
//Pass the job object somehow to the "MessageHandler" below.
processor.ProcessErrorAsync += ErrorHandler;
await processor.StartProcessingAsync();
Console.WriteLine("Wait for a minute and then press any key to end the processing");
Console.ReadKey();
Console.WriteLine("\nStopping the receiver...");
await processor.StopProcessingAsync();
Console.WriteLine("Stopped receiving messages");
}
finally
{
await processor.DisposeAsync();
await client.DisposeAsync();
}
});
以及新消息到达时调用的处理程序:
static async Task MessageHandler(ProcessMessageEventArgs args)
{
//I need the "job" object from my loop above here.
}
这个概念通常是如何运作的,我在 Microsoft 的 this website 上了解到。
我的第一个问题:
但即使这没问题,我还有一个更重要的任务:
我需要以某种方式将循环中的“作业”对象作为参数传递给消息处理程序。
但我目前不知道如何存档。对此有什么建议吗?
答案 0 :(得分:1)
这种方法可以吗,还是我跑错了方向?我可以这样做吗?
是的,你可以这样做。要记住的一件事是实例化多个 ServiceBusClient
实例,每个实例都会导致建立新连接而不是使用相同的连接。我不知道主题(工作)的数量可能有多大,但如果它很大,最终会导致连接匮乏。
我需要以某种方式将循环中的“作业”对象作为参数传递给消息处理程序。但我目前不知道如何存档。对此有什么建议吗?
这不是 ServiceBusProcessor
的设计方式。除了需要处理的传入消息之外,它不会接收任何其他内容。如果您需要一个作业 ID,它应该是消息负载/元数据的一部分。如果您需要知道它来自哪个实体,您可以添加订阅过滤器操作以添加带有标识符的自定义标头。另一种方法是需要包装 ServiceBusProcessor
以保留作业 ID/订阅标识符并在事件处理程序中使用它。