问题来源
长期以来,.NET开发者都通过下面的方式发送http请求:
using (var httpClient = new HttpClient())
{
var response = await httpClient.GetAsync(uri);
//do something with response
}
这段代码理论上来说遵守了C#的最佳实践,HttpClient是IDisposable类型,所以我们通过using语法糖来使用HttpClient。微软官方的文档也提到:
As a rule, when you use an IDisposable object, you should declare and instantiate it in a using statement
可是,当我们试图运行下面的测试:
public async Task SendRequest()
{
Console.WriteLine("Starting reqeust");
for(int i = 0; i<10; i++)
{
using(var client = new HttpClient())
{
var result = await client.GetAsync("http://www.baidu.com");
Console.WriteLine(result.StatusCode);
}
}
Console.WriteLine("Reqeust done");
}
此时在terminal下列出所有端口:
netstat -ap tcp | grep -i "time_wait"
<img src="https://www.cnblogs.com/images/cnblogs_com/xiandnc/1255906/o_Jietu20190103-110826@2x.png" alt="" width="600" height="800"> 你会发现本地开启了10个端口,这说明HttpClient的工作原理其实跟我们认为的IDisposable是有区别的,如果你把HttpClient用作大规模的Http请求,实际上会创建很多个Http连接,而且这些资源并不能被立即释放。一个显而易见的改进方法是共享同一个HttpClient实例,从而达到节约socket资源的目的。 ```csharp private static readonly HttpClient _client = new HttpClient(); public async Task SendRequest2() { _testOutputHelper.WriteLine("Start request");
for(int i = 0; i<10; i++)
{
var result = await _client.GetAsync("http://www.baidu.com");
Console.WriteLine(result.StatusCode);
}
_testOutputHelper.WriteLine("Request done");
}
这个方案似乎解决了问题,使用单例的HttpClient的确会减少Socket资源,但是这个方案会引发新的问题:由于这个Http连接始终保持连接状态,所以当请求地址的DNS发生更新的时候并不会应用到这个Http连接上。这个问题在微服务,高可用时代更加常见[Singeton HttpClient doesn't respect DNS changes](https://github.com/dotnet/corefx/issues/11224)。
最终,一个叫做[HttpClientFactory](https://github.com/aspnet/HttpClientFactory)的开源实现用来彻底解决这个问题。微软也将HttpClientFactory集成在了.NET Core中。
##在.NET Core中创建HttpClient
#### 1.添加Nuget
Microsoft.Extensions.Http
#### 2.在Dependency Injection容器中注册服务
```csharp
services.AddHttpClient();
3. 使用构造器注入使用IhttpClientFactory
public class BasicUsage
{
private readonly IHttpClientFactory _clientFactory;
public BasicUsage(IHttpClientFactory clientFactory)
{
_clientFactory = clientFactory;
}
public async Task SendRequest()
{
var request = new HttpRequestMessage(HttpMethod.Get,
"http://www.baidu.com");
var client = _clientFactory.CreateClient();
var response = await client.SendAsync(request);
//do something for response
}
}
4. 使用Named HttpClient
由于我们在DI容器中注册了唯一的HttpClientFactory,意味着通过HttpClientFactory创建出来的HttpClient可能是同一个配置和参数,如果你需要不同配置的HttpClient,你可以通过“起名字的”的方式注册不同的HttpClient。
services.AddHttpClient("baidu", c =>
{
c.BaseAddress = new Uri("https://www.baidu.com");
c.DefaultRequestHeaders.Add("Accept", "application/json");
});
一旦注册了一个名叫“baidu"的HttpClient,你就可以通过下面的方式来建创建HttpClient:
var client = _clientFactory.CreateClient("baidu");
5.集成Polly
Polly是一个用来故障处理库,它允许开发者在Http请求中添加“重试、熔断器、超时等”策略。 先添加Nuget:
Microsoft.Extensions.Http.Polly
添加策略:
var timeout = Policy.TimeoutAsync<HttpResponseMessage>(TimeSpan.FromSeconds(10));
services.AddHttpClient("baidu")
.AddPolicyHandler(request => timeout)
.AddTransientHttpErrorPolicy(p=>p.RetryAsync(3));
当然还有一些高阶用法,详见Initiate HTTP requests,总之HttpClientFactory提供了一种高效实用HttpClient的方式,如果你还在自己new HttpClient,请赶快试试新的方案吧。
原文出处:https://www.cnblogs.com/xiandnc/p/10215187.html
来源:oschina
链接:https://my.oschina.net/u/4339939/blog/3271714