自從HttpClient誕生依賴,它的使用方式一直備受爭議,framework版本時(shí)代產(chǎn)生過相當(dāng)多經(jīng)典的錯(cuò)誤使用案例,包括Tcp鏈接耗盡、DNS更改無感知等問題。有興趣的同學(xué)自行查找研究。在.NETCORE版本中,提供了IHttpClientFactory用來創(chuàng)建HttpClient以解決之前的種種問題。那么我們一起看一下它的用法。
使用方式
注:這種方式經(jīng)測試貌似不適用控制臺程序。
示例代碼
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 創(chuàng)建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創(chuàng)建的客戶端默認(rèn)記錄所有請求的日志消息,并每個(gè)客戶端的日志類別會包含客戶端名稱,例如,名為 MyNamedClient 的客戶端記錄類別為“System.Net.Http.HttpClient.MyNamedClient.LogicalHandler”的消息。
請求管道
同framework時(shí)代的HttpClient一樣支持管道處理。需要自定義一個(gè)派生自 DelegatingHandler 的類,并實(shí)現(xiàn) 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的時(shí)候注入進(jìn)去
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每次調(diào)用CreateHttpClient都會返回一個(gè)全新的HttpClient實(shí)例。而負(fù)責(zé)http請求處理的核心HttpMessageHandler將會有工廠管理在一個(gè)池中,可以重復(fù)使用,以減少資源消耗。HttpMessageHandler默認(rèn)生成期為兩分鐘。可以在每個(gè)命名客戶端上重寫默認(rèn)值:
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpClient("extendedhandlerlifetime")
.SetHandlerLifetime(TimeSpan.FromMinutes(5));
}
Polly支持
Polly是一款為.NET提供恢復(fù)能力和瞬態(tài)故障處理的庫,它的各種策略應(yīng)用(重試、斷路器、超時(shí)、回退等)。IHttpClientFactory增加了對其的支持,它的nuget包為: Microsoft.Extensions.Http.Polly。注入方式如下:
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpClient<UnreliableEndpointCallerService>()
.AddTransientHttpErrorPolicy(p =>
p.WaitAndRetryAsync(3, _ => TimeSpan.FromMilliseconds(600)));
}
更詳細(xì)的結(jié)合使用請參考: https://github.com/App-vNext/Polly/wiki/Polly-and-HttpClientFactory