2017-03-21 104 views
0

我正在使用改裝波利調用restful API的,我想知道Refits ApiException的重試(如果有的話)策略應該是什麼?Refit ApiException的最佳重試策略?

public static PolicyWrap MyRetryPolicy() 
{ 
     // Try few times with little more time between... maybe the 
     // connection issue gets resolved 
     var wireServerNetworkIssue = Policy.Handle<WebException>() 
            .WaitAndRetryAsync(new[] { 
            TimeSpan.FromSeconds(1), 
            TimeSpan.FromSeconds(2), 
            TimeSpan.FromSeconds(4)}); 
     var policyList = new List<Policy>(); 

     // But if there is something wrong with the api 
     // I should do what (if general)? 
     var api = Policy.Handle<ApiException>() 
        .RetryAsync(1, onRetry: async (exception, i) => 
        { 
         await Task.Run(() => 
         { 
          // What would be normal to do here? 
          // Try again or do some circuit braking? 
         }); 
        }); 

     policyList.Add(wireServerNetworkIssue); 
     policyList.Add(api); 

     return Policy.Wrap(policyList.ToArray()); 
} 

然後,我使用這樣的

try 
{ 
    myApi = RestService.For<MyApi>("api base url"); 
    var policyWrapper = Policies.Policies.MyRetryPolicyWrapper(); 
    var response = await policy.ExecuteAsync(() => myApi.SendReceiptAsync(receipt)); 
} 
catch (ApiException apiEx) 
{ 
    //Do something if the retry policy did´t fix it. 
} 
catch (WebException webEx) 
{ 
    //Do something if the retry policy did´t fix it. 
} 

問題

會是怎樣的ApiExceptions一個正常的重試策略?你會只是剎車或在什麼情況下你會做一些恢復?

答案可能是「這取決於你的服務回報」但我不得不問。

+0

你不應該需要等待'Task.Run(()=> {});'在你原來的問題的'onRetry'委託(除非您有意在後臺線程可能運行'onRetry'行動)。在委託中簡單使用'await'會爲委託提供一個基於「任務」的返回類型。另外,如果你想onretry行動異步運行,使用波莉的'.RetryAsync(...)'重載服用'onRetryAsync'參數,而不是'onRetry'。 –

回答

1

如果返回的ApiException包含有意義的HttpStatusCode StatusCode屬性,您當然可以選擇哪些StatusCodes值得重試;在Polly readme建議:

int[] httpStatusCodesWorthRetrying = {408, 500, 502, 503, 504}; 

對於ApiException的具體到所謂的,只有那些什麼特定的API-錯誤表示知識的API,可以指導是否進行重試。

如果您選擇對某些類型的太多例外進行斷路,應通過在您的PolicyWrap中包裝斷路器,而不是在重試策略的onRetry委託內實現。波莉論述'爲什麼會斷路?' here,並鏈接到readme circuit-breaker section腳下的其他一些斷路器博客帖子。