问题描述
这是我要批量插入的代码:
private async Task AddSubscription(EnableOrdisableSubscriptionCommand command,SubscriptionAction subscriptionAction,IList<int> notificationCategoryTypes)
{
List<Task> bulkOperations = new List<Task>();
foreach (var notificationCategory in notificationCategoryTypes)
{
var notificationTypes = Utility.GetNotificationTypes((NotificationCategoryType)notificationCategory);
foreach (var notificationType in notificationTypes)
{
foreach (var payerAccountSubscriptions in command.Subscriptions)
{
if (payerAccountSubscriptions.AccountNumbers?.Any() ?? false)
{
foreach (var accountNumber in payerAccountSubscriptions.AccountNumbers.Where(a => !string.IsNullOrEmpty(a)))
{
bulkOperations.Add(_repository.Create(subscriptionAction,notificationType,payerAccountSubscriptions.ColCoId,payerAccountSubscriptions.PayerNumber,accountNumber,command.UserRole,command.UserId));
}
}
else
{
bulkOperations.Add(_repository.Create(subscriptionAction,null,command.UserId));
}
}
}
}
await Task.WhenAll(bulkOperations);
}
public Task<ItemResponse<T>> CreateItemAsync(T item,string partitionkeyvalue)
{
return _container.CreateItemAsync<T>(item,new PartitionKey(partitionkeyvalue));
}
local.settings.json:
{
"IsEncrypted": false,"Values": {
"AzureWebJobsstorage": "UseDevelopmentStorage=true","AzureWebJobsDashboard": "UseDevelopmentStorage=true","FUNCTIONS_WORKER_RUNTIME": "dotnet",//localhost
"CosmosDbId": "Notifications","CosmoDbAuthKey": "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==","CosmoDbEndpoint": "https://localhost:8081/",}
}
我已经安装了Azure Cosmos DB仿真器。
[2020年8月31日6:49:10] System.Private.CoreLib:发生异常时 执行函数:EnableOrdisableSubscriptions。 Microsoft.Azure.Cosmos.Client:响应状态代码未指示 成功:ServiceUnavailable(503);子状态:0;活动
解决方法
请确保在.NET SDK中注意以下几点:
- 初始化单例DocumentClient
- 使用直接连接和TCP协议(ConnectionMode.Direct和ConnectionProtocol.Tcp)
- 并行使用100个任务(取决于您的硬件)
- 将DocumentClient构造函数中的MaxConnectionLimit增加到一个高值,例如1000个连接
- 打开gcServer
- 确保您的馆藏具有适当的预配置吞吐量(和良好的分区键)
您现在可以直接将批量执行程序库用于批量操作-https://docs.microsoft.com/en-us/azure/cosmos-db/bulk-executor-dot-net
,我在遵循 Cosmos DB SQL API 入门指南后遇到了同样的问题。
修复方法是指定 ConnectionMode = ConnectionMode.Gateway
var cosmosClient = new CosmosClient(EndpointUrl,AuthorizationKey,new CosmosClientOptions() { AllowBulkExecution = true,ConnectionMode = ConnectionMode.Gateway });