使用UpsertItemAsync上传到CosmosDB的.NET Azure函数应用程序速度非常慢,尤其是与Python的CosmosClient相比

2024-10-03 04:34:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个在Azure上运行的.NET函数应用程序,它将数据上传到CosmosDB,如下所示:

foreach (var message in messages)
{
    try
    {
        await notificationsContainer.UpserItemAsync(message, message.NTID);
    }
    catch (Exception exception)
    {
        //...
    }
}

UpsertItemAsync是一个包装器:

public async Task<T> UpsertItemAsync(T document, string partitionKey)
{
    ItemResponse<T> response = await _container.UpsertItemAsync<T>(document, new PartitionKey(partitionKey));
    return response.Resource;
}

我正在测试6500条消息。将640条(!)消息上载到数据库需要16分钟。同时,使用Python的CosmosClient,调用

container.create_item(message)

乘以6500,需要131秒才能完成

此外,功能应用程序正在Azure上运行,CosmosClient设置为直接连接模式:

 CosmosClient client = clientBuilder
    .WithConnectionModeDirect()
    .WithThrottlingRetryOptions(new TimeSpan(0, 0, 0, 0, config.MaxRetryWaitTimeInMilliSeconds), config.MaxRetryCount)
    .WithBulkExecution(true)
    .Build();

python脚本在on-prem虚拟机上运行时

对这种表演上的巨大差异有什么解释?功能应用程序不是非常慢吗


Tags: 功能config应用程序消息messagenewnetresponse
1条回答
网友
1楼 · 发布于 2024-10-03 04:34:05

您的问题是,您正在启用大容量模式(.WithBulkExecution(true)),但对每个操作都执行await

当使用批量模式(referencehttps://devblogs.microsoft.com/cosmosdb/introducing-bulk-support-in-the-net-sdk/)时,您需要创建这些操作,但不需要单独等待。比如:

List<Task> operations = new List<Task>();
foreach (var message in messages)
{
    operations.Add(notificationsContainer.UpserItemAsync(message, message.NTID));
}

try
{
    await Task.WhenAll(operations);
}
catch(Exception ex)
{
    //...
}

如果要执行单个操作,请选择该选项或禁用批量模式

相关问题 更多 >