DocumentDB TransientFaultHandling最佳实践

INN*_*VTV 6 c# azure azure-cosmosdb

我一直在为受限制的DocumentDB客户端调用编写非常详细的重试逻辑.

下面的示例是10次重试尝试的常见示例.

我的问题有两个方面: 这是最好的做法,是否有一种不那么冗长的方式来处理这个问题?我看到有一个Microsoft.Azure.Documents.Client.TransientFaultHandling nuget包应该用更少的代码实现相同的结果,但我在StackOverflow或Google上找不到任何示例,似乎没有任何明确的文档可用来自微软.

int maxRetryAttempts = 10;

while (maxRetryAttempts > 0)
{
    try
    {
        // Attempt to call DocumentDB Method
        // ---[DocumentDB Method Here]---
    }
    catch (DocumentClientException de)
    {
        if (de.StatusCode.HasValue)
        {
            var statusCode = (int)de.StatusCode;

            if (statusCode == 429 || statusCode == 503)
            {
                //Sleep for retry amount
                Thread.Sleep(de.RetryAfter);

                //Decrement max retry attempts 
                maxRetryAttempts--;
            }

        }
    }
    catch (AggregateException ae)
    {                    
        foreach (Exception ex in ae.InnerExceptions)
        {
            if (ex is DocumentClientException)
            {
                var documentClientException = ex as DocumentClientException;
                var statusCode = (int)documentClientException.StatusCode;
                if (statusCode == 429 || statusCode == 503)
                {
                    //Sleep for retry amount
                    Thread.Sleep(documentClientException.RetryAfter);

                    //Decrement max retry attempts 
                    maxRetryAttempts--;
                }
                else
                {
                    throw;
                }
            }
        }
    }
}

if (maxRetryAttempts < 0)
{
    //Max retry attempts reached
}
Run Code Online (Sandbox Code Playgroud)

And*_*Liu 7

您可以使用DocumentU数据迁移工具的Github存储库中的TransientFaultHandling Nuget包找到示例代码:

https://github.com/Azure/azure-documentdb-datamigrationtool/blob/master/DocumentDb/Microsoft.DataTransfer.DocumentDb.FunctionalTests/DocumentDbHelper.cs

看起来像这样:

private static IReliableReadWriteDocumentClient CreateClient(IDocumentDbConnectionSettings connectionSettings)
{
    return new DocumentClient(new Uri(connectionSettings.AccountEndpoint), connectionSettings.AccountKey)
        .AsReliable(new FixedInterval(10, TimeSpan.FromSeconds(1)));
}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢Andrew.这正是我所需要的.有没有办法找回成功通话后发生的重试次数?我看到我收回了使用的RU数量以及其他一些信息,但是知道需要多少重试次数将帮助我调整我的呼叫. (2认同)