【问题标题】:DocumentDB TransientFaultHandling Best PracticeDocumentDB TransientFaultHandling 最佳实践
【发布时间】:2015-06-26 05:38:37
【问题描述】:

我一直在为受限制的 DocumentDB 客户端调用编写非常冗长的重试逻辑。

下面的例子是一个常见的例子,重试了 10 次。

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

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
}

【问题讨论】:

  • 在您的catch 块中,当展开AggregateException 时,您会默默地丢弃所有非DocumentClientException 异常。这是故意的吗?我本以为会冒出未知的异常。

标签: c# azure azure-cosmosdb


【解决方案1】:

您可以使用文档数据库数据迁移工具的 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)));
}

【讨论】:

  • 谢谢安德鲁。这正是我所需要的。有什么方法可以取回成功调用后发生的重试次数?我看到我找回了使用的 RU 数量以及其他一些信息,但是知道需要多少次重试将有助于我调整我的调用。
  • 美丽。可靠和“不可靠”的客户现在拥有不可共享的代码库,尽管它们是平等的。直到你使用dynamic,哈哈。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-05
  • 2014-12-21
  • 2010-12-23
  • 2010-10-14
  • 2023-03-19
  • 2011-11-08
相关资源
最近更新 更多