.NetCore中HttpClient使用Polly重试的简单实现

Polly是一个非常强大的组件,今天我们来使用HttpClient结合Polly做一个失败重试的简单示例。为啥有此示例,实在是网上的教程太乱了,尝试了好多次才成功。应该是我看官方文档有点费劲,英文差,靠百度翻译,一边看注释然后一边翻译!好累好累。

 在实际开发中,.NetCore开发环境,我们使用HttpClient的方法,一般分3种方式:工厂模式,命名客户端模式,类型客户端模式。今天我们来使用命名客户端模式结合Polly做重试。

步骤1:添加2个包:Polly和Microsoft.Extensions.Http.Polly

其实只要引入Microsoft.Extensions.Http.Polly 这一个包就可以了,他会自动将Polly引入。我之所以单独再添加Polly,是看到Polly有最新版本,而Microsoft.Extensions.Http.Polly自动引入的Polly包不是最新版(强迫症啊)。

步骤2:配置服务

StartUp的ConfigureServices里添加代码,先看代码再解说:

            services.AddHttpClient("myhttpclienttest", client =>
            { 
                client.BaseAddress = new Uri("http://localhost:9002/");
            }).AddTransientHttpErrorPolicy(builder =>
            {

                return builder.RetryAsync(20, (res, Index) =>
                    {
                        Console.WriteLine($"执行错误,异常行为:{res?.Result}");
                        Console.WriteLine($"第{Index}次重试");

                    }); 
            })

                ;

AddHttpClient("myhttpclienttest",xxxx) 这个模式就是命名客户端模式,可以配置其地址或者请求头配置等;

AddTransientHttpErrorPolicy这个方法就是在HttpClient客户端添加Polly的失败重试策略。builder配置重试次数,这里是20次,只要1个参数即可;若想要打印日志,也是可以的,看上面的代码。

注:1、一般的做法肯定是要加日志的,为了便于排查问题和确保代码的正确性,不然谁也不知道自己写的代码,是否真的管用啊。

2、失败重试的条件默认是 对方(这里的http://localhost:9002/)的Http状态值返回500,5xxx(服务器错误 Server Errors)和408 (请求超时 request timeout);当然也可以自定义,这里先不做扩展。

3、为了演示方面,我将重试直接设置20次。

 

第3步:就可以实际操作httpclient的具体方法了

写个简单的demo代码吧:

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;

namespace HttpClientDemo.Controllers
{


    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
         
        private readonly ILogger<WeatherForecastController> _logger;

        private readonly IHttpClientFactory _clientFactory; 
        public WeatherForecastController(ILogger<WeatherForecastController> logger, IHttpClientFactory clientFactory)
        {
            _logger = logger;
            _clientFactory = clientFactory; 

        }

        /// <summary>
        /// 测试HttpClient和Polly
        /// </summary>
        /// <returns></returns>

        [HttpGet]
        public async Task<string> Get()
        {
            try
            {
                Console.WriteLine("请求处理开始。。。。"); 

                var client = _clientFactory.CreateClient("myhttpclienttest");
           
                var htmlStr = await client.GetStringAsync("nav/ops23");
                Console.WriteLine("请求处理结束。。。。");
                 
                return "";
            }
            catch (Exception ex)
            {

                throw;
            }
        } 
    }
}

为了对方的地址返回500,我将http://localhost:9002/站点下的appsettings.json 删掉。就直接报503异常了。或者是调用一个不存在的站点。

运行后,看效果能看到日志了。

 

------------------------------

升级篇

若有多个HttpClient,为了公用Polly策略,我们将策略稍稍独立出来,然后让每个HttpClient命名客户端builder添加进去。代码如下:

还是在Startup.ConfigureServices方法里;

            var RetryPolicy2 = Policy.HandleResult<HttpResponseMessage>(message =>
            {
                return (message.StatusCode == HttpStatusCode.InternalServerError || message.StatusCode==HttpStatusCode.RequestTimeout);

            }).RetryAsync(20, (res, Index) =>
           {
               Console.WriteLine($"执行错误,异常行为:{res?.Result}");
               Console.WriteLine($"2第{Index}次重试");

           });

            services.AddHttpClient("myhttpclienttest", client =>
            {
                client.BaseAddress = new Uri("http://localhost:9002/");
            })
                .AddPolicyHandler(RetryPolicy2)
                ;

我们先定义了RetryPolicy2  这个策略,然后在HttpClient后面AddPolicyHandler就可以了。

 

posted @ 2021-07-14 12:46  沐雪架构师  阅读(1294)  评论(0编辑  收藏  举报