c# - 异步 ServiceBusTrigger 的好处
问题描述
我正在开发微服务(使用 Azure Function Apps),其中包含ServiceBusTrigger
基于 Azure Functions 的功能,这些功能在将消息插入Service Bus Queue时触发。
我正在尝试确定将输出值绑定到多个目标(例如 CosmosDB和IoT Hub)的最佳方式。该方法是否被标记为异步将决定我应该如何解决这个问题。
据我所知,通常使用异步函数处理输出绑定的方式是使用[return: ...]
注释;但是,在我的用例中,我需要将两个不同的值返回到两个单独的目标(例如 CosmosDb 和 IoT Hub)。我不认为这是我可以通过返回值绑定或输出变量绑定来实现的,因为你不能有一个out
带有异步方法的参数,你可以使用该[return: ...]
方法定义多个返回值。
看来我唯一的选择(如果我走异步路线)是在 Azure 函数中手动调用 SDK 方法来调用独立于任何输出值的服务。我试图避免这样做,因为输出绑定是首选方法。
我在创建基于全新ServiceBusTrigger
的 Azure 函数时所做的观察是,生成的方法签名默认情况下未标记为async
。
这与标记为开箱即用的HttpTrigger
不同。async
有人可以帮我理解这样做的原因吗?一个与另一个相关的缩放影响是什么?
我从传统意义上理解为什么您通常将 a 标记HttpTrigger
为异步;但是,我不明白为什么ServiceBusTrigger
不是异步的原因
在继续巩固我的输出方法之前,我需要了解这一点。
解决方案
我不认为有/没有async
功能的模板对它们有任何推理。并且根据您的代码,您的功能可能会更有效。
阅读此线程以获取有关async/await
in 函数的更多详细信息。
至于您的主要问题,您只需为 CosmosDB 和 IoT Hub 输出绑定绑定到不同的对象。
- 对于 CosmosDB,您必须改为绑定到
IAsyncCollector
,如文档中所示
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);
}
}
}
}
- 对于事件中心,您必须改为绑定到
IAsyncCollector
,如文档中所示
[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));
}
}
推荐阅读
- php - 如何在 PHP 中的 if 中正确使用 isset?
- java - Spring Boot 无法发现我的 JPA 存储库。然而,IntelliJ 在发现的 bean 中显示了它
- multithreading - 熊猫功能的多处理星图死锁
- python - Python 在字符串中查找模式并将其替换为列表中的其他模式字符串
- php - andWhere 条件学说 CreateQueryBuilder 的问题
- selenium - 启用 JavaScript 的 Selenium 不会跳过
- angular - Angular - NgRx - difference between .select(...) and .pipe(select...)
- javascript - Why do my onclick function only work once?
- postgresql - How to connect postgresql database server deployed on azure cloud to an app service on azure which uses prisma db?
- mysql - mysql - Set temporary variable to store more than 1 records?