azure - 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.");
}
}
}
解决方案
触发器不会重试文档批次,您可能正在接收相同文档的更新。
如果您检查thisDocument.GetPropertyValue<int>("_ts")
哪个是操作的时间戳,您将看到这些是不同的值。
Change Feed 包含插入和更新操作,如果您的架构多次更新同一个文档,那么预计在 Change Feed 中会有多个条目用于相同的文档 id。
此外,不相关的会很好,您CloudStorageAccount
在每次执行时创建一个实例,一个好的模式是通过依赖注入或延迟初始化来维护单个实例并共享它(参见https://docs.microsoft .com/azure/azure-functions/manage-connections)。
推荐阅读
- c# - C# 获取 CreatedAtRoute 的返回对象
- java - 在这个 Java 程序上工作以了解 SMTP 的工作原理(不允许使用 JavaMail)
- swift - 当表格不可见时阻止/推迟来自 NSFetchedResultsController 的表格视图更新
- c - 尽管指向 malloc 的内存,为什么指针“忘记”它的值
- wpf - 动态切换 WPF UI 控件
- android - 覆盖“顶级功能”
- azure - 绕过 Azure AD SSO“选择帐户”提示并自动登录 cookie 存储的用户?
- mysql - 如何将 SQL 中的 2 个表与 1 个公共列组合在一起,而其他列中没有关系?
- c++ - 为什么 std::distance() 用于 std:list
::iterator 在最后一个在第一个之前时不返回负数? - maven-plugin - pmd maven 插件不尊重 exclude-cpd.properties