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

时间:2012-03-28 09:24:39

标签: 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)

如果此代码重试,请告知我们,谢谢

1 个答案:

答案 0 :(得分:5)

设置重试策略时,指定将控制退休的类,在您的情况下为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;
        }
    }