gpt4 book ai didi

c# - 异步 ServiceBusTrigger 的优点

转载 作者:行者123 更新时间:2023-12-03 02:51:15 29 4
gpt4 key购买 nike

我正在开发微服务(使用 Azure Function Apps),其中包含基于 ServiceBusTrigger 的 Azure Functions,当消息插入服务总线队列时会触发服务总线队列

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

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

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

我在创建基于 ServiceBusTrigger 的全新 Azure Function 时观察到,生成的方法签名标记为 async 默认情况下。

这与 HttpTrigger 不同,后者标记为开箱即用的async

有人可以帮我理解其中的原因吗?其中一种与另一种相关的扩展影响是什么?

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

我需要先理解这一点,然后才能继续巩固我的输出方法。

最佳答案

我不认为带有/不带有async函数的模板有任何理由。根据您的代码,您的函数可能会更有效。
阅读 this thread有关函数中async/await的更多详细信息。

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

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));
}
}

关于c# - 异步 ServiceBusTrigger 的优点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56012456/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com