适用于 Azure Functions 2.x 的 Azure Cosmos DB 触发器Azure Cosmos DB trigger for Azure Functions 2.x

Azure Cosmos DB 触发器使用 Azure Cosmos DB 更改源来侦听跨分区的插入和更新。The Azure Cosmos DB Trigger uses the Azure Cosmos DB Change Feed to listen for inserts and updates across partitions. 更改源发布插入和更新,不发布删除。The change feed publishes inserts and updates, not deletions.

有关设置和配置详细信息,请参阅概述For information on setup and configuration details, see the overview.

以下示例演示了一个 C# 函数。当指定数据库和集合中存在插入或更新操作时,会调用该函数。The following example shows a C# function that is invoked when there are inserts or updates in the specified database and collection.

using Microsoft.Azure.Documents;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;

namespace CosmosDBSamplesV2
{
    public static class CosmosTrigger
    {
        [FunctionName("CosmosTrigger")]
        public static void Run([CosmosDBTrigger(
            databaseName: "ToDoItems",
            collectionName: "Items",
            ConnectionStringSetting = "CosmosDBConnection",
            LeaseCollectionName = "leases",
            CreateLeaseCollectionIfNotExists = true)]IReadOnlyList<Document> documents,
            ILogger log)
        {
            if (documents != null && documents.Count > 0)
            {
                log.LogInformation($"Documents modified: {documents.Count}");
                log.LogInformation($"First document Id: {documents[0].Id}");
            }
        }
    }
}

特性和注释Attributes and annotations

C# 类库中,使用 CosmosDBTrigger 特性。In C# class libraries, use the CosmosDBTrigger attribute.

该特性的构造函数采用数据库名称和集合名称。The attribute's constructor takes the database name and collection name. 有关这些设置以及可以配置的其他属性的信息,请参阅触发器 - 配置For information about those settings and other properties that you can configure, see Trigger - configuration. 下面是某个方法签名中的 CosmosDBTrigger 特性示例:Here's a CosmosDBTrigger attribute example in a method signature:

    [FunctionName("DocumentUpdates")]
    public static void Run(
        [CosmosDBTrigger("database", "collection", ConnectionStringSetting = "myCosmosDB")]
    IReadOnlyList<Document> documents,
        ILogger log)
    {
        ...
    }

有关完整示例,请参阅触发器For a complete example, see Trigger.

配置Configuration

下表解释了在 function.json 文件和 CosmosDBTrigger 特性中设置的绑定配置属性。The following table explains the binding configuration properties that you set in the function.json file and the CosmosDBTrigger attribute.

function.json 属性function.json property Attribute 属性Attribute property 说明Description
typetype 不适用n/a 必须设置为 cosmosDBTriggerMust be set to cosmosDBTrigger.
directiondirection 不适用n/a 必须设置为 inMust be set to in. 在 Azure 门户中创建触发器时,会自动设置该参数。This parameter is set automatically when you create the trigger in the Azure portal.
namename 不适用n/a 函数代码中使用的变量名称,表示发生更改的文档列表。The variable name used in function code that represents the list of documents with changes.
connectionStringSettingconnectionStringSetting ConnectionStringSettingConnectionStringSetting 应用设置的名称,该应用设置包含用于连接到受监视的 Azure Cosmos DB 帐户的连接字符串。The name of an app setting that contains the connection string used to connect to the Azure Cosmos DB account being monitored.
databaseNamedatabaseName DatabaseNameDatabaseName 带有受监视的集合的 Azure Cosmos DB 数据库的名称。The name of the Azure Cosmos DB database with the collection being monitored.
collectionNamecollectionName CollectionNameCollectionName 受监视的集合的名称。The name of the collection being monitored.
leaseConnectionStringSettingleaseConnectionStringSetting LeaseConnectionStringSettingLeaseConnectionStringSetting (可选)应用设置的名称,该设置包含保存租用集合的 Azure Cosmos DB 帐户的连接字符串。(Optional) The name of an app setting that contains the connection string to the Azure Cosmos DB account that holds the lease collection. 未设置时,使用 connectionStringSetting 值。When not set, the connectionStringSetting value is used. 在门户中创建绑定时,将自动设置该参数。This parameter is automatically set when the binding is created in the portal. 用于租用集合的连接字符串必须具有写入权限。The connection string for the leases collection must have write permissions.
leaseDatabaseNameleaseDatabaseName LeaseDatabaseNameLeaseDatabaseName (可选)数据库的名称,该数据库包含用于存储租用的集合。(Optional) The name of the database that holds the collection used to store leases. 未设置时,使用 databaseName 设置的值。When not set, the value of the databaseName setting is used. 在门户中创建绑定时,将自动设置该参数。This parameter is automatically set when the binding is created in the portal.
leaseCollectionNameleaseCollectionName LeaseCollectionNameLeaseCollectionName (可选)用于存储租用的集合的名称。(Optional) The name of the collection used to store leases. 未设置时,使用值 leasesWhen not set, the value leases is used.
createLeaseCollectionIfNotExistscreateLeaseCollectionIfNotExists CreateLeaseCollectionIfNotExistsCreateLeaseCollectionIfNotExists (可选)设置为 true 时,如果租用集合并不存在,将自动创建该集合。(Optional) When set to true, the leases collection is automatically created when it doesn't already exist. 默认值为 falseThe default value is false.
leasesCollectionThroughputleasesCollectionThroughput LeasesCollectionThroughputLeasesCollectionThroughput (可选)在创建租用集合时,定义要分配的请求单位的数量。(Optional) Defines the number of Request Units to assign when the leases collection is created. 仅当 createLeaseCollectionIfNotExists 设置为 true 时,才会使用此设置。This setting is only used when createLeaseCollectionIfNotExists is set to true. 使用门户创建绑定时,将自动设置该参数。This parameter is automatically set when the binding is created using the portal.
leaseCollectionPrefixleaseCollectionPrefix LeaseCollectionPrefixLeaseCollectionPrefix (可选)设置后,该值将作为前缀添加到在此函数的租约集合中创建的租约。(Optional) When set, the value is added as a prefix to the leases created in the Lease collection for this Function. 使用前缀可让两个不同的 Azure 函数通过不同的前缀来共享同一个租约集合。Using a prefix allows two separate Azure Functions to share the same Lease collection by using different prefixes.
feedPollDelayfeedPollDelay FeedPollDelayFeedPollDelay (可选)在所有当前更改清空后,每两次在分区中轮询源上的新更改的延迟时间(以毫秒为单位)。(Optional) The time (in milliseconds) for the delay between polling a partition for new changes on the feed, after all current changes are drained. 默认值为 5,000 毫秒(5 秒)。Default is 5,000 milliseconds, or 5 seconds.
leaseAcquireIntervalleaseAcquireInterval LeaseAcquireIntervalLeaseAcquireInterval (可选)设置后,此项以毫秒为单位定义启动一个计算任务的时间间隔(前提是分区在已知的主机实例中均匀分布)。(Optional) When set, it defines, in milliseconds, the interval to kick off a task to compute if partitions are distributed evenly among known host instances. 默认为 13000(13 秒)。Default is 13000 (13 seconds).
leaseExpirationIntervalleaseExpirationInterval LeaseExpirationIntervalLeaseExpirationInterval (可选)设置后,此项以毫秒为单位定义在表示分区的租用上进行租用的时间间隔。(Optional) When set, it defines, in milliseconds, the interval for which the lease is taken on a lease representing a partition. 如果在此时间间隔内不续订租用,则该租用会过期,分区的所有权会转移到另一个实例。If the lease is not renewed within this interval, it will cause it to expire and ownership of the partition will move to another instance. 默认为 60000(60 秒)。Default is 60000 (60 seconds).
leaseRenewIntervalleaseRenewInterval LeaseRenewIntervalLeaseRenewInterval (可选)设置后,此项以毫秒为单位定义当前由实例拥有的分区的所有租用的续订时间间隔。(Optional) When set, it defines, in milliseconds, the renew interval for all leases for partitions currently held by an instance. 默认为 17000(17 秒)。Default is 17000 (17 seconds).
checkpointFrequencycheckpointFrequency CheckpointFrequencyCheckpointFrequency (可选)设置后,此项以毫秒为单位定义租用检查点的时间间隔。(Optional) When set, it defines, in milliseconds, the interval between lease checkpoints. 默认为始终在进行每个 Function 调用之后进行检查。Default is always after each Function call.
maxItemsPerInvocationmaxItemsPerInvocation MaxItemsPerInvocationMaxItemsPerInvocation (可选)设置后,此属性会对每次函数调用收到的项目的最大数目进行设置。(Optional) When set, this property sets the maximum number of items received per Function call. 如果受监视集合中的操作通过存储过程执行,则在从更改源读取项时,会保留事务范围If operations in the monitored collection are performed through stored procedures, transaction scope is preserved when reading items from the Change Feed. 因此,收到的项数可能高于指定的值,通过同一事务更改的项会通过某个原子批处理操作返回。As a result, the number of items received could be higher than the specified value so that the items changed by the same transaction are returned as part of one atomic batch.
startFromBeginningstartFromBeginning StartFromBeginningStartFromBeginning (可选)此选项告知触发器要从集合的更改历史记录开头位置读取更改,而不是从当前时间开始读取。(Optional) This option tells the Trigger to read changes from the beginning of the collection's change history instead of starting at the current time. 从开头位置读取仅在触发器首次启动时起作用,因为在后续运行中,已存储检查点。Reading from the beginning only works the first time the Trigger starts, as in subsequent runs, the checkpoints are already stored. 如果已经创建租约,则将此选项设置为 true 将不起作用。Setting this option to true when there are leases already created has no effect.
preferredLocationspreferredLocations PreferredLocationsPreferredLocations (可选)为 Azure Cosmos DB 服务中的异地复制数据库帐户定义首选位置(区域)。(Optional) Defines preferred locations (regions) for geo-replicated database accounts in the Azure Cosmos DB service. 值应以逗号分隔。Values should be comma-separated.

在本地进行开发时,应用设置将取 local.settings.json 文件的值。When you're developing locally, app settings go into the local.settings.json file.

使用情况Usage

触发器需要第二个集合,该集合用于存储各分区的_租用_。The trigger requires a second collection that it uses to store leases over the partitions. 必须提供受监视的集合和包含租用的集合,触发器才能正常工作。Both the collection being monitored and the collection that contains the leases must be available for the trigger to work.

重要

如果多个函数都配置为对同一集合使用 Cosmos DB 触发器,则每个函数都应使用专用租用集合,否则应该为每个函数指定不同的 LeaseCollectionPrefixIf multiple functions are configured to use a Cosmos DB trigger for the same collection, each of the functions should use a dedicated lease collection or specify a different LeaseCollectionPrefix for each function. 否则,将只触发其中一个函数。Otherwise, only one of the functions will be triggered. 有关前缀的信息,请参阅“配置”部分For information about the prefix, see the Configuration section.

该触发器并不指示是更新还是插入文档,它仅提供文档本身。The trigger doesn't indicate whether a document was updated or inserted, it just provides the document itself. 如果需要以不同方式处理更新和插入,可通过实现用于插入或更新的时间戳字段来执行该操作。If you need to handle updates and inserts differently, you could do that by implementing timestamp fields for insertion or update.

后续步骤Next steps