写Cosmos DB时遇到一个奇怪的问题。第一次写入似乎因ResultCode
中的Faulted
而失败。但是,似乎写操作确实有效,并且重试时ResultCode
是409
冲突。
这是个问题,因为我将其用作幂等检查,因此我们随后不执行第三方调用。
任何想法为什么我们会得到这种行为?看来我们需要关闭设置/选项以防止重试。
我们有一个非常简单的文档客户端设置
return new DocumentClient(new Uri(configuration["CosmosDBSettings:EndpointUri"]), configuration["CosmosDBSettings:AuthenticationKey"]);
插入文档的代码为:
public async Task<bool> TryInsertReference(Guid paymentReference)
{
try
{
await this.documentClient.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(DatabaseId, VoidCollectionId), new Payment { PaymentReference = paymentReference });
return true;
}
catch (DocumentClientException e) when (e.StatusCode == HttpStatusCode.Conflict)
{
return false;
}
}
public async Task Initialise()
{
await CreateDatabaseIfNotExistsAsync();
await this.CreateCollectionIfNotExistsAsync(GuaranteeCollectionId);
await this.CreateCollectionIfNotExistsAsync(VoidCollectionId);
}
private async Task CreateDatabaseIfNotExistsAsync()
{
try
{
await documentClient.ReadDatabaseAsync(UriFactory.CreateDatabaseUri(DatabaseId));
}
catch (DocumentClientException e)
{
if (e.StatusCode == HttpStatusCode.NotFound)
{
await documentClient.CreateDatabaseAsync(new Database { Id = DatabaseId });
}
else
{
throw;
}
}
}
private async Task CreateCollectionIfNotExistsAsync(string collectionId)
{
try
{
await documentClient.ReadDocumentCollectionAsync(UriFactory.CreateDocumentCollectionUri(DatabaseId, collectionId));
}
catch (DocumentClientException e)
{
if (e.StatusCode == HttpStatusCode.NotFound)
{
await documentClient.CreateDocumentCollectionAsync(UriFactory.CreateDatabaseUri(DatabaseId), new DocumentCollection { Id = collectionId, DefaultTimeToLive = this.timeToLive });
}
else
{
throw;
}
}
}