84487600 2020-08-16
前言
自从HttpClient诞生依赖,它的使用方式一直备受争议,framework版本时代产生过相当多经典的错误使用案例,包括Tcp链接耗尽、DNS更改无感知等问题。有兴趣的同学自行查找研究。在.NETCORE版本中,提供了IHttpClientFactory用来创建HttpClient以解决之前的种种问题。那么我们一起看一下它的用法。
使用方式
示例代码
public void ConfigureServices(IServiceCollection services) { //普通注入 serviceCollection.AddHttpClient(); //命名注入 serviceCollection.AddHttpClient(Constants.SERVICE_USERACCOUNT, (serviceProvider, c) => { var configuration = serviceProvider.GetRequiredService<IConfiguration>(); c.BaseAddress = new Uri(configuration.GetValue<string>("ServiceApiBaseAddress:UserAccountService")); }); //类型化客户端 services.AddHttpClient<TypedClientService>(); } public class AccreditationService { private IHttpClientFactory _httpClientFactory; private const string _officialAccreName = "manage/CommitAgencyOfficialOrder"; private const string _abandonAccUserName = "info/AbandonUserAccreditationInfo"; public AccreditationService(IHttpClientFactory clientFactory) { _httpClientFactory = clientFactory; } public async Task<string> CommitAgentOfficial(CommitAgencyOfficialOrderRequest request) { //使用factory 创建httpclient var httpClient = _httpClientFactory.CreateClient(Constants.SERVICE_ACCREDITATION); var response = await httpClient.PostAsJsonAsync(_officialAccreName, request); if (!response.IsSuccessStatusCode) return string.Empty; var result = await response.Content.ReadAsAsync<AccreditationApiResponse<CommitAgencyOfficialOrderResult>>(); if (result.ReturnCode != "0") return string.Empty; return result.Data.OrderNo; } }
命名化客户端方式直接注入的是HttpClient而非HttpClientFactory
public class TypedClientService { private HttpClient _httpClient; public TypedClientService(HttpClient httpClient) { _httpClient = httpClient; } }
Logging
通过IHttpClientFactory创建的客户端默认记录所有请求的日志消息,并每个客户端的日志类别会包含客户端名称,例如,名为 MyNamedClient 的客户端记录类别为“System.Net.Http.HttpClient.MyNamedClient.LogicalHandler”的消息。
请求管道
同framework时代的HttpClient一样支持管道处理。需要自定义一个派生自DelegatingHandler的类,并实现SendAsync方法。例如下面的例子
public class ValidateHeaderHandler : DelegatingHandler { protected override async Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { if (!request.Headers.Contains("X-API-KEY")) { return new HttpResponseMessage(HttpStatusCode.BadRequest) { Content = new StringContent( "You must supply an API key header called X-API-KEY") }; } return await base.SendAsync(request, cancellationToken); } }
在AddHttpClient的时候注入进去
public void ConfigureServices(IServiceCollection services) { services.AddTransient<ValidateHeaderHandler>(); services.AddHttpClient("externalservice", c => { // Assume this is an "external" service which requires an API KEY c.BaseAddress = new Uri("https://localhost:5001/"); }) .AddHttpMessageHandler<ValidateHeaderHandler>(); }
原理和生存周期
IHttpClientFactory每次调用CreateHttpClient都会返回一个全新的HttpClient实例。而负责http请求处理的核心HttpMessageHandler将会有工厂管理在一个池中,可以重复使用,以减少资源消耗。HttpMessageHandler默认生成期为两分钟。可以在每个命名客户端上重写默认值:
public void ConfigureServices(IServiceCollection services) { services.AddHttpClient("extendedhandlerlifetime") .SetHandlerLifetime(TimeSpan.FromMinutes(5)); }
Polly支持
Polly是一款为.NET提供恢复能力和瞬态故障处理的库,它的各种策略应用(重试、断路器、超时、回退等)。IHttpClientFactory增加了对其的支持,它的nuget包为: Microsoft.Extensions.Http.Polly。注入方式如下:
public void ConfigureServices(IServiceCollection services) { services.AddHttpClient<UnreliableEndpointCallerService>() .AddTransientHttpErrorPolicy(p => p.WaitAndRetryAsync(3, _ => TimeSpan.FromMilliseconds(600))); }
更详细的结合使用请参考:https://github.com/App-vNext/Polly/wiki/Polly-and-HttpClientFactory
总结
创建一个 HttpClient 实例,这个实例需要调用 Dispose 方法释放资源,这里使用了 using 语句。接着调用 GetAsync,给它传递要调用的方法的地址,向服务器发送 Get 请求。