一个 Azure Function,可以侦听所有容器的 Cosmos DB 更改提要

One Azure Function that can listen to Cosmos DB Change Feed for all containers

现在我有一个 Cosmos DB,它具有三个不同的容器,因此我使用三个不同的函数来侦听来自这个 Cosmos DB 的 Change Feed 事件。

将来我的容器数量将从 3 个增加到 100 个。

那么,是否可以有一个函数来侦听所有容器中的所有更改,并且可以检测来自哪些容器的更改?

简而言之:没有

Change feed in Azure Cosmos DB is a persistent record of changes to a container in the order they occur. Change feed support in Azure Cosmos DB works by listening to an Azure Cosmos container for any changes.

Change feed is available for each logical partition key within the container, and it can be distributed across one or more consumers for parallel processing.

Change feed in Azure Cosmos DB 上的文档清楚地指出更改源是针对一个特定容器的。

但是,您可能可以采用不同的方法来解决您的问题。最重要的问题是:实际上是什么您要解决的问题?

如果您需要使用函数处理 Cosmos DB 中的更改,我可以想象用于处理更改的逻辑对于每种类型的数据可能(将)不同。所以对于每个容器。如果这是不是的情况,数据不必在不同的容器中?

一个选项可以是创建一个定时器触发的函数,它将是 Reading change feed with a pull model. This enables you to loop the containers in that Function and prepare processing the changes per container (for instance by putting the information in a queue or using Durable Functions with the Fan-Out/Fan-In pattern)。

Cosmos DB 的推荐模式是拥有一个或几个数据容器,并通过 属性 值在逻辑上对数据进行分区,而不是将数据分段到多个容器中。如果可能的话,出于更改提要和其他原因,值得审查提议的设计,看看是否有合并容器并避免这种痛苦的方法。

也就是说,如果必须支持数量未知且数量不断增加的容器,一种动态实现的方法是通过 SDK 使用 Change Feed Processor。使用 GetChangeFeedProcessorBuilder 实例化处理器实例时,您可以提供容器名称作为参数。给定所有目标容器的配置或发现列表,可以创建多个更改源处理器实例并运行并行。

这可能 hosted 有多种方式。考虑使用带有 IHostedService 的 ASP.NET 核心应用程序,并在这种情况下避免使用 Azure Functions。