首页 > 解决方案 > 异步 ServiceBusTrigger 的好处

问题描述

我正在开发微服务(使用 Azure Function Apps),其中包含ServiceBusTrigger基于 Azure Functions 的功能,这些功能在将消息插入Service Bus Queue时触发。

我正在尝试确定将输出值绑定到多个目标(例如 CosmosDBIoT Hub)的最佳方式。该方法是否被标记为异步将决定我应该如何解决这个问题。

据我所知,通常使用异步函数处理输出绑定的方式是使用[return: ...]注释;但是,在我的用例中,我需要将两个不同的值返回到两个单独的目标(例如 CosmosDb 和 IoT Hub)。我不认为这是我可以通过返回值绑定或输出变量绑定来实现的,因为你不能有一个out带有异步方法的参数,你可以使用该[return: ...]方法定义多个返回值。

看来我唯一的选择(如果我走异步路线)是在 Azure 函数中手动调用 SDK 方法来调用独立于任何输出值的服务。我试图避免这样做,因为输出绑定是首选方法。

我在创建基于全新ServiceBusTrigger的 Azure 函数时所做的观察是,生成的方法签名默认情况下标记为async

这与标记为开箱即用的HttpTrigger不同。async

有人可以帮我理解这样做的原因吗?一个与另一个相关的缩放影响是什么?

我从传统意义上理解为什么您通常将 a 标记HttpTrigger为异步;但是,我不明白为什么ServiceBusTrigger不是异步的原因

在继续巩固我的输出方法之前,我需要了解这一点。

标签: c#azureazure-functionsazure-servicebus-queues

解决方案


我不认为有/没有async功能的模板对它们有任何推理。并且根据您的代码,您的功能可能会更有效。
阅读此线程以获取有关async/awaitin 函数的更多详细信息。

至于您的主要问题,您只需为 CosmosDB 和 IoT Hub 输出绑定绑定到不同的对象。

using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;

namespace CosmosDBSamplesV2
{
    public static class WriteDocsIAsyncCollector
    {
        [FunctionName("WriteDocsIAsyncCollector")]
        public static async Task Run(
            [QueueTrigger("todoqueueforwritemulti")] ToDoItem[] toDoItemsIn,
            [CosmosDB(
                databaseName: "ToDoItems",
                collectionName: "Items",
                ConnectionStringSetting = "CosmosDBConnection")]
                IAsyncCollector<ToDoItem> toDoItemsOut,
            ILogger log)
        {
            log.LogInformation($"C# Queue trigger function processed {toDoItemsIn?.Length} items");

            foreach (ToDoItem toDoItem in toDoItemsIn)
            {
                log.LogInformation($"Description={toDoItem.Description}");
                await toDoItemsOut.AddAsync(toDoItem);
            }
        }
    }
}
[FunctionName("EH2EH")]
public static async Task Run(
    [EventHubTrigger("source", Connection = "EventHubConnectionAppSetting")] EventData[] events,
    [EventHub("dest", Connection = "EventHubConnectionAppSetting")]IAsyncCollector<string> outputEvents,
    ILogger log)
{
    foreach (EventData eventData in events)
    {
        // do some processing:
        var myProcessedEvent = DoSomething(eventData);

        // then send the message
        await outputEvents.AddAsync(JsonConvert.SerializeObject(myProcessedEvent));
    }
}

推荐阅读