c# - Microsoft.Practices.TransientFaultHandling.RetryPolicy 的正确代码是什么?

标签 c# azure azure-storage

我使用以下代码:

创建重试策略,当出错时,1秒后重试,然后等待3秒,然后5秒。基于Azure SLA,10秒内重试必须成功(没有限制,我确信这一点。因为错误甚至发生在还没有流量的唯一分区和表上)

var retryStrategy = new Incremental(3, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2));
var FaultHandlingRetryPolicy = new RetryPolicy<StorageTransientErrorDetectionStrategy>(retryStrategy);

然后我使用这段代码来获取数据

FaultHandlingRetryPolicy .ExecuteAction(() =>
        {
            var results = (from q in Query select new q).ToList();
        });

我不知道是否重试,因为错误日志未显示

错误:

System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it 70.37.127.112:443
   at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
   at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception)
   --- End of inner exception stack trace ---
   at System.Net.HttpWebRequest.GetResponse()
   at System.Data.Services.Client.QueryResult.Execute()
   at System.Data.Services.Client.DataServiceRequest.Execute[TElement](DataServiceContext context, QueryComponents queryComponents)
   at System.Data.Services.Client.DataServiceQuery`1.Execute()
   at System.Data.Services.Client.DataServiceQuery`1.GetEnumerator()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at Microsoft.Practices.TransientFaultHandling.RetryPolicy.<>c__DisplayClass1.<ExecuteAction>b__0()
   at Microsoft.Practices.TransientFaultHandling.RetryPolicy.ExecuteAction[TResult](Func`1 func)

请告诉我此代码是否会重试,谢谢

最佳答案

当您设置重试策略时,您可以指定控制退出的类,在您的情况下,它是 StorageTransientErrorDetectionStrategy

每次在ExecuteAction()方法中抛出异常时,此类将决定是否可以重试。例如,某些异常是暂时的,因此不值得重试。

要实际跟踪重试次数,您可以使用如下代码:

FaultHandlingRetryPolicy.Retrying += (obj, eventArgs) =>
            {
                Console.Writeline("Retrying, CurrentRetryCount = {0} , Exception = {1}", eventArgs.CurrentRetryCount, eventArgs.LastException.Message);
            };

更新

您可以像这样创建自己的错误处理策略并使用它来代替标准策略。 但是你必须调整错误以适应你的场景,这些对我有用。

    public class CustomSqlAzureTransientErrorDetectionStrategy : ITransientErrorDetectionStrategy
    {
        private readonly SqlAzureTransientErrorDetectionStrategy _normalStrategy =
            new SqlAzureTransientErrorDetectionStrategy();

        public bool IsTransient(Exception ex)
        {
            if (_normalStrategy.IsTransient(ex))
                return true;

            //do our custom logic
            if (ex is SqlException)
            {
                var sqEx = ex as SqlException;
                if (sqEx.Message.Contains("The timeout period elapsed prior to completion of the operation or the server is not responding") ||
                    sqEx.Message.Contains("An existing connection was forcibly closed by the remote host") ||
                    sqEx.Message.Contains("The service has encountered an error processing your request. Please try again") ||
                    sqEx.Message.Contains("Timeout expired") ||
                    sqEx.Message.Contains("was deadlocked on lock resources with another process and has been chosen as the deadlock victim") ||
                    sqEx.Message.Contains("A transport-level error has occurred when receiving results from the server"))
                {                        
                    return true;
                }
            }

            return false;
        }
    }

关于c# - Microsoft.Practices.TransientFaultHandling.RetryPolicy 的正确代码是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9904588/

相关文章:

c# - 从 ICollectionView 中删除项目

c# - RedisClient.Get<T> C# 与 ServiceStack.Redis 的性能

c# - ASP.NET 烦人的 URL 编码字符串

c# - 如何从 xamarin android 中的超链接 TextView 中删除下划线

node.js - 默认文档不在 Azure 托管的 Node Web 应用程序上提供

c# - Windows Azure : web application on several instances, 身份验证?

c# - 如果路径中的目录不存在,CloudFile.Exists()/ExistsAsync() 会抛出 403(未经授权)?

azure - 将 ARM 模板资源部署到一个资源组,并将 secret 部署到另一资源组中的 key 保管库

具有 IP 范围限制的 Azure Blob SAS

c# - AzureStorageFile.Uri 未返回具有特殊字 rune 件名的正确 Uri,导致 404 响应