.NET 5 中的示例 Azure 函数使用 IAsyncCollector<T> 将多条消息写入服务总线

Sample Azure Function in .NET 5 using IAsyncCollector<T>to write multiple messages to a service bus

有人可以为 .NET 5 中的 Azure Functions 提供示例代码,该函数使用 IAsyncCollector 将多条消息添加到服务总线吗?

根据 documentation:

IAsyncCollector 当前不支持进程外/工作进程 SDK

Because .NET isolated projects run in a separate worker process, bindings can't take advantage of rich binding classes, such as ICollector, IAsyncCollector, and CloudBlockBlob. There's also no direct support for types inherited from underlying service SDKs, such as DocumentClient and BrokeredMessage. Instead, bindings rely on strings, arrays, and serializable types, such as plain old class objects (POCOs).

documentation is not clear about how to achieve it. This issue 强调您可以通过在集合 属性 上使用带有 ServiceBusOutput 属性的专用 class 将序列化的多个值作为单独的消息发送。例如:

[Function("OneToMany")]
public static DispatchedMessages Run([ServiceBusTrigger("myqueue",
    Connection = "AzureServiceBus")] string myQueueItem,
    FunctionContext context)
{
    // Generate 5 messages
    var messages = new List<MyMessage>();
    for (var i = 0; i < 5; i++)
    {
        var message = new MyMessage { Value = $"Message #{i}" };
        messages.Add(message);
    }

    return new DispatchedMessages
    { 
        Messages = messages.Select(x => JsonSerializer.Serialize(x)) 
    };
}

每条消息的类型为 MyMessage:

class MyMessage
{
    public string Value { get; set; }
}

并且该函数将 return 它作为一个 DispatchedMessages 类型,它有一个 属性 Messages 代表所有需要作为序列化发送的消息字符串:

public class DispatchedMessages
{
    [ServiceBusOutput(queueOrTopicName: "dest", Connection = "AzureServiceBus")]
    public IEnumerable<string> Messages { get; set; }
}

请注意,连接字符串名称是必需的,因为默认情况下 Functions SDK 将尝试使用 AzureWebJobsServiceBus 连接字符串名称。

功能完成后,dest队列中将有5条消息,序列化MyMessage条消息的JSON条内容。