asp.net core using HttpClientFactory Polly realized blown downgrade

Foreword

In the NET Core2.1 after update also increased a lot, of course HttpClientFactory part of the update. Although HttpClient that implements Disposable , but when using it by way of using the packaging blocks usually not the best choice. Processing HttpClient , the underlying socket socket is not released immediately. The HttpClient class is created a plurality of requests not reused. Requires a different base address, different HTTP while other scenes headers and the request for personalized operation, it is necessary to manage multiple hands HttpClient instance, in order to simplify management HttpClient instance, .NET 2.1 Core provides a new HTTPClientFactory - it can create , buffer and processing HttpClient instance.

What is HttpClientFactory

From ASPNET Core beginning, Polly and IHttpClientFastory integration. HttpClientFastory is a simplified management and use of HttpClientory . ASP.Net team with the words: "AN opinionated for Creating Factory's HttpClient instances" (for creating best practices HttpClient instance factory )

  • Providing naming and configuration logic HttpClient object center position. For example, you can configure pre-configured to access a specific micro-services client (service agent).
  • By delegating handler HttpClient and implemented based on Polly middleware to take advantage of Polly resilience strategy, the concept came middleware encoded.
  • HttpClient has been commissioned by the concept handlers, these handlers can be chained together for outgoing HTTP requests. You will HTTP client registers to the factory, and can be used Polly handler Polly strategy for Retry , CircuitBreakers and so on.
  • Life cycle management, HttpClientMessageHandlers to avoid management HttpClient the above-mentioned problems can occur when their life cycle / problem.

HttpClientFactory simple to use

  • Startup Add
services.AddHttpClient();
  • Create an HttpClient object via IHttpClientFactory, operating behind as the old, but it does not need to be concerned about the release of resources
using Microsoft.AspNetCore.Mvc;
using System.Net.Http;
using System.Threading.Tasks;

namespace HttpClientFactoryPolly.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        private readonly IHttpClientFactory _httpClientFactory;
        public ValuesController(IHttpClientFactory httpClientFactory)
        {
            this._httpClientFactory = httpClientFactory;
        }

        // GET api/values
        [HttpGet]
        public async Task<ActionResult<string>> Get()
        {
            var client = _httpClientFactory.CreateClient();
            var result =await client.GetStringAsync("https://www.microsoft.com/zh-cn/");
            return result;
        }


    }
}

Configuration HttpClientFactory Polly

Here the use of named clients demonstrate the chestnuts (if the application requires a number of different HttpClient usage (usage of each configuration is different), as the case may use a named client. Can HttpClient designated Startup.ConfigureServices configuration name registration in .)

  • Package
PM> Install-package Microsoft.Extensions.Http.Polly

Startup

   services.AddHttpClient("github",c=> {
                //基址
                c.BaseAddress = new System.Uri("https://api.github.com/");
                // Github API versioning
                c.DefaultRequestHeaders.Add("Accept", "application/vnd.github.v3+json");
                // Github requires a user-agent
                c.DefaultRequestHeaders.Add("User-Agent", "HttpClientFactory-Sample");
            });
[HttpGet("{id}")]
public async Task<ActionResult<string>> Get(int id)
{
        var request = new HttpRequestMessage(HttpMethod.Get,
       "repos/aspnet/docs/pulls");

        var client = _httpClientFactory.CreateClient("github");

        var response = await client.SendAsync(request);
        var result =await response.Content.ReadAsStringAsync();
        return result;
}
  • Retry mechanism
services.AddHttpClient("github", c =>
    {
        //基址
        c.BaseAddress = new System.Uri("https://api.github.com/");
        // Github API versioning
        c.DefaultRequestHeaders.Add("Accept", "application/vnd.github.v3+json");
        // Github requires a user-agent
       c.DefaultRequestHeaders.Add("User-Agent", "HttpClientFactory-Sample");
        //AddTransientHttpErrorPolicy主要是处理Http请求的错误,如HTTP 5XX 的状态码,HTTP 408 的状态码 以及System.Net.Http.HttpRequestException异常
        }).AddTransientHttpErrorPolicy(p =>
        //WaitAndRetryAsync参数的意思是:每次重试时等待的睡眠持续时间。
    p.WaitAndRetryAsync(3, _ => TimeSpan.FromMilliseconds(600)));

Results are as follows

  • Fuse downgrade timeout
services.AddHttpClient("test", c =>
  {
    //基址
    c.BaseAddress = new System.Uri("http://localhost:5000/");
    // Github API versioning
    c.DefaultRequestHeaders.Add("Accept", "application/vnd.github.v3+json");
    // Github requires a user-agent
    c.DefaultRequestHeaders.Add("User-Agent", "HttpClientFactory-Sample");
    })
     // 降级
    .AddPolicyHandler(Policy<HttpResponseMessage>.Handle<Exception>().FallbackAsync(fallbackResponse, async b =>
    {
        Console.WriteLine($"fallback here {b.Exception.Message}");
    }))
    // 熔断
    .AddPolicyHandler(Policy<HttpResponseMessage>.Handle<Exception>().CircuitBreakerAsync(2, TimeSpan.FromSeconds(4), (ex, ts) =>
    {
        Console.WriteLine($"break here {ts.TotalMilliseconds}");
    }, () =>
    {
        Console.WriteLine($"reset here ");
    }))
    // 超时
    .AddPolicyHandler(Policy.TimeoutAsync<HttpResponseMessage>(1));

    }

Set downgrade policy when there is any abnormal returns fallback

Set fuse policy abnormal when abnormal two times in a row, fuse 4s;

Set timeout policy, the request timeout 1s, the default timeout throws TimeoutRejectedException;

Results are as follows

Overview

Address Example: https://github.com/fhcodegit/HttpClientFactoryPolly
Polly: https://github.com/App-vNext/Polly
Reference: https://blog.csdn.net/qq_42606051/article/details/81698662

Guess you like

Origin www.cnblogs.com/yyfh/p/11548776.html