我本人和同事都承担了查找Azure Table Storage连接重试逻辑的任务。经过一番搜索,我发现了这个非常酷的企业库套件,其中包含Microsoft.Practices.TransientFaultHandling命名空间。

在给出一些代码示例之后,我最终创建了一个Incremental重试策略,并使用retryPolicyExecuteAction回调处理程序包装了我们的一个存储调用:

/// <inheritdoc />
public void SaveSetting(int userId, string bookId, string settingId, string itemId, JObject value)
{
    // Define your retry strategy: retry 5 times, starting 1 second apart, adding 2 seconds to the interval each retry.
    var retryStrategy = new Incremental(5, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2));

    var storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting(StorageConnectionStringName));

    try
    {
        retryPolicy.ExecuteAction(() =>
        {
                var tableClient = storageAccount.CreateCloudTableClient();

                var table = tableClient.GetTableReference(SettingsTableName);

                table.CreateIfNotExists();

                var entity = new Models.Azure.Setting
                {
                    PartitionKey = GetPartitionKey(userId, bookId),
                    RowKey = GetRowKey(settingId, itemId),
                    UserId = userId,
                    BookId = bookId.ToLowerInvariant(),
                    SettingId = settingId.ToLowerInvariant(),
                    ItemId = itemId.ToLowerInvariant(),
                    Value = value.ToString(Formatting.None)
                };

                table.Execute(TableOperation.InsertOrReplace(entity));
            });
        }
        catch (StorageException exception)
        {
            ExceptionHelpers.CheckForPropertyValueTooLargeMessage(exception);

            throw;
        }
    }
}

感觉很棒,我去看我的同事,他自鸣得意地说,我们可以做同样的事情而不必包含Enterprise Library,因为CloudTableClient对象已经具有重试策略的 setter 。他的代码最终看起来像:
/// <inheritdoc />
public void SaveSetting(int userId, string bookId, string settingId, string itemId, JObject value)
{
        var storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting(StorageConnectionStringName));
        var tableClient = storageAccount.CreateCloudTableClient();

        // set retry for the connection
        tableClient.RetryPolicy = new ExponentialRetry(TimeSpan.FromSeconds(2), 3);

        var table = tableClient.GetTableReference(SettingsTableName);

        table.CreateIfNotExists();

        var entity = new Models.Azure.Setting
        {
            PartitionKey = GetPartitionKey(userId, bookId),
            RowKey = GetRowKey(settingId, itemId),
            UserId = userId,
            BookId = bookId.ToLowerInvariant(),
            SettingId = settingId.ToLowerInvariant(),
            ItemId = itemId.ToLowerInvariant(),
            Value = value.ToString(Formatting.None)
        };

        try
        {
            table.Execute(TableOperation.InsertOrReplace(entity));
        }
        catch (StorageException exception)
        {
            ExceptionHelpers.CheckForPropertyValueTooLargeMessage(exception);

            throw;
        }
}

我的问题:

除了它们的实现之外,这两种方法之间是否还有主要区别?他们俩似乎都实现了相同的目标,但是在某些情况下,最好使用一个而不是另一个吗?

最佳答案

从功能上讲,两者是相同的-如果出现暂时性错误,它们都会重试请求。但是几乎没有区别:

存储客户端库中的

  • 重试策略处理仅处理存储操作的重试,而 transient 故障处理重试不仅处理存储操作,而且在发生瞬时错误的情况下重试SQL Azure,服务总线和缓存操作。因此,如果您有一个项目在使用更多的存储空间,但只想采用一种方法来处理 transient 错误,则可能要使用 transient 故障处理应用程序块。
  • 我喜欢 transient 故障处理块的一件事是,您可以拦截重试操作,而重试策略是无法执行的。例如,看下面的代码:
        var retryManager = EnterpriseLibraryContainer.Current.GetInstance<RetryManager>();
        var retryPolicy = retryManager.GetRetryPolicy<StorageTransientErrorDetectionStrategy>(ConfigurationHelper.ReadFromServiceConfigFile(Constants.DefaultRetryStrategyForTableStorageOperationsKey));
        retryPolicy.Retrying += (sender, args) =>
        {
            // Log details of the retry.
            var message = string.Format(CultureInfo.InvariantCulture, TableOperationRetryTraceFormat, "TableStorageHelper::CreateTableIfNotExist", storageAccount.Credentials.AccountName,
                tableName, args.CurrentRetryCount, args.Delay);
            TraceHelper.TraceError(message, args.LastException);
        };
        try
        {
            var isTableCreated = retryPolicy.ExecuteAction(() =>
            {
                var table = storageAccount.CreateCloudTableClient().GetTableReference(tableName);
                return table.CreateIfNotExists(requestOptions, operationContext);
            });
            return isTableCreated;
        }
        catch (Exception)
        {
            throw;
        }
    

  • 在上面的代码示例中,我可以拦截重试操作,并在需要的地方做一些事情。对于存储客户端库,这是不可能的。

    综上所述,通常建议使用存储客户端库重试策略来重试存储操作,因为它是软件包不可或缺的一部分,因此将与库的最新更改保持同步。

    10-05 20:31
    查看更多