手记

[Asp.net core]使用Polly网络请求异常重试

摘要

在网络传输过程中,不能保证所有的请求都能正确的被服务端接受或者处理,那么进行简单的重试可以进行简单的补救。比如现在大部分支付功能,在支付成功之后,需要回调我们网站的接口,并且要求我们的接口给一个类似成功的响应,支付端收到我们的成功响应,就不再进行重试请求了。

比如:支付宝文档中有这么一段描述

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分钟后进行最后尝试。否则认为网络不正常,则抛出异常,进行日志记录。

 总结

Polly支持多种重试策略,感兴趣的可以移步这里。

https://www.cnblogs.com/CreateMyself/p/7589397.html

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

0人推荐
随时随地看视频
慕课网APP