首页 > 解决方案 > Azure Function CosmosDb 触发器一遍又一遍地处理相同的文档

问题描述

我有一个由 CosmosDb 插入/更新触发的函数,我将每个文档复制到一个存储 blob。调试时,该函数会一遍又一遍地为相同的少数文档触发。

我尝试限制处理的文档数量,但这使得它只能一遍又一遍地处理相同的 N 个文档。我尝试在触发器集合(和租约集合)上提高 RU,但没有效果。

[FunctionName("Function1")]
        public async static Task Run([CosmosDBTrigger(
            databaseName: "Events",
            collectionName: "DomainEvents",
            ConnectionStringSetting = "cosmosConnectionString",
            CreateLeaseCollectionIfNotExists = true,
            LeaseCollectionName = "DomainEventLeases")]IReadOnlyList<Document> input, ILogger log, ExecutionContext context)
        {
            if (input != null && input.Count > 0)
            {
                var config = new ConfigurationBuilder()
                 .SetBasePath(context.FunctionAppDirectory)
                 .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                 .AddEnvironmentVariables()
                 .Build();

                CloudStorageAccount cloudStorageAccount;

                if (CloudStorageAccount.TryParse(config["StorageConnectionAppSetting"], out cloudStorageAccount))
                {
                    var client = cloudStorageAccount.CreateCloudBlobClient();
                    var container = client.GetContainerReference("wormauditlog");

                    foreach(var thisDocument in input)
                    {
                        var blob = container.GetBlockBlobReference(thisDocument.Id);

                        try
                        {
                            await blob.UploadFromByteArrayAsync(thisDocument.ToByteArray(), 0, thisDocument.ToByteArray().Length);
                        }
                        catch(Exception e)
                        {
                            throw;
                        }
                    }
                }
                else
                {
                    throw new FunctionInvocationException("Bad storage connection string.");
                }

            }
        }

标签: azureazure-functionsazure-cosmosdbazure-triggers

解决方案


触发器不会重试文档批次,您可能正在接收相同文档的更新。

如果您检查thisDocument.GetPropertyValue<int>("_ts")哪个是操作的时间戳,您将看到这些是不同的值。

Change Feed 包含插入和更新操作,如果您的架构多次更新同一个文档,那么预计在 Change Feed 中会有多个条目用于相同的文档 id。

此外,不相关的会很好,您CloudStorageAccount在每次执行时创建一个实例,一个好的模式是通过依赖注入或延迟初始化来维护单个实例并共享它(参见https://docs.microsoft .com/azure/azure-functions/manage-connections)。


推荐阅读