[Asp.net core]使用Polly網絡請求異常重試

摘要

在網絡傳輸過程當中,不能保證全部的請求都能正確的被服務端接受或者處理,那麼進行簡單的重試能夠進行簡單的補救。好比如今大部分支付功能,在支付成功以後,須要回調咱們網站的接口,而且要求咱們的接口給一個相似成功的響應,支付端收到咱們的成功響應,就再也不進行重試請求了。html

好比:支付寶文檔中有這麼一段描述web

Polly簡單實用網絡

private ILog _log; /// <summary>
        /// 重試時間點 /// </summary>
        private TimeSpan[] _retryTimes = new[] { TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(20), TimeSpan.FromMinutes(1) }; /// <summary>
        /// 提交文本 /// </summary>
        /// <param name="url"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public string PostTxt(string url, Dictionary<string, string> paras) { try { 
 string data = ConvertDic2QueryString(paras); byte[] byteArray = Encoding.UTF8.GetBytes(data);
var retry4TimePolicy = Polly.Policy.Handle<WebException>().WaitAndRetry( _retryTimes, (ex, ts, i, context) => { _log.Info(new LogModel { Content = $"Request:{url},data:{ConvertDic2QueryString(paras)},第{i}次重試", userId= "", Op = "posttxt" }); }); return retry4TimePolicy.Execute(() => {  HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.ContentType = "application/x-www-form-urlencoded"; request.Method = "POST"; request.ContentLength = byteArray.Length; request.Timeout = 60000; if (url.StartsWith("https")) { request.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true; } Stream requestStream = request.GetRequestStream(); requestStream.Write(byteArray, 0, byteArray.Length); HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse(); StreamReader reader = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8); String sResult = reader.ReadToEnd(); requestStream.Close(); reader.Close(); webResponse.Close(); return sResult; }); } catch (WebException ex) { throw ex; } }
public string ConvertDic2QueryString(Dictionary<string, string> dic) { if (dic == null) { return string.Empty; } StringBuilder sb = new StringBuilder(); foreach (var key in dic.Keys) { sb.AppendFormat("{0}={1}&", key, HttpUtility.UrlEncode(dic[key])); } return sb.ToString().TrimEnd('&'); }

能夠相似上面的一種請求,在捕獲到webException異常時,立馬重試一次,檢查網絡是否正常,若是仍不能正確進行請求,下次5s,10s,20s,進行嘗試,若是仍不正常,則在1分鐘後進行最後嘗試。不然認爲網絡不正常,則拋出異常,進行日誌記錄。app

 總結

Polly支持多種重試策略,感興趣的能夠移步這裏。post

http://www.javashuo.com/article/p-opmxxgua-ee.html網站

http://www.cnblogs.com/xishuai/p/asp-net-core-polly.htmlui

相關文章
相關標籤/搜索