ASP.NET Core-通过HttpClientFactory使用HttpClient

概述:

在.NET Framwork中使用HttpClient直接这样使用 using(var client = new HttpClient()){} ,高并发时频繁创建socket,连接来不及释放,socket被耗尽,就会出现问题。

所以不用频繁创建HttpClient对象,要复用,可以设置成静态,并且设置成长连接,我之前的教程有介绍。这样使用有一点问题是DNS更新会失效

在Core中使用HttpClientFactory创建HttpClient,目的也是复用HttpClient。顾名思义 HttpClientFactory 就是 HttpClient 的工厂,内部已经帮我们处理好了对 HttpClient 的管理,不需要我们人工进行对象释放,同时,支持自定义请求头,支持DNS更新等等等。

HttpClientFactory使用方法:

用法1,直接使用HttpClientFactory

1、在startup中注册

public void ConfigureServices(IServiceCollection services)
   {
       //other codes

       services.AddHttpClient("client_1",config=>  //这里指定的 name=client_1 ,可以方便我们后期服用该实例
       {
           config.BaseAddress= new Uri("http://client_1.com");
           config.DefaultRequestHeaders.Add("header_1","header_1");
       });
       services.AddHttpClient("client_2",config=>
       {
           config.BaseAddress= new Uri("http://client_2.com");
           config.DefaultRequestHeaders.Add("header_2","header_2");
       });
       services.AddHttpClient();
   }

2、Controller中使用

public class TestController : ControllerBase
{
 private readonly IHttpClientFactory _httpClient;
 public TestController(IHttpClientFactory httpClient)
 {
     _httpClient = httpClient;
 }

 public async Task<ActionResult> Test()
 {
     var client = _httpClient.CreateClient("client_1"); //复用在 Startup 中定义的 client_1 的 httpclient
     var result = await client.GetStringAsync("/page1.html");

     var client2 = _httpClient.CreateClient(); //新建一个 HttpClient
     var result2 = await client.GetStringAsync("http://www.site.com/XXX.html");

     return null;
 }
}

 用法2,自定义类封装HttpClient

1、自定义类封装HttpClient

public interface ISampleClient
    {
        Task<string> GetData();
    }

    public class SampleClient : ISampleClient
    {
        private readonly HttpClient _client;

        public SampleClient(IHttpClientFactory httpClientFactory)
        {
            var httpClient = httpClientFactory.CreateClient();
            httpClient.BaseAddress = new Uri("https://www.taobao.com/");
            //httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
            //httpClient.DefaultRequestHeaders.Add("User-Agent", "HttpClientFactory-Sample");
            _client = httpClient;
        }

        public async Task<string> GetData()
        {
            return await _client.GetStringAsync("/");
        }
    }

2、Startup中注册SampleClient

services.AddHttpClient<ISampleClient, SampleClient>();

3、调用

public class ValuesController : Controller
{
    private readonly ISampleClient  _sampleClient;;

    public ValuesController(ISampleClient  sampleClient)
    {
        _sampleClient = sampleClient;
    }

    [HttpGet]
    public async Task<ActionResult> Get()
    {
        string result = await _sampleClient.GetData();
        return Ok(result);
    }
}

参考:https://blog.zhuliang.ltd/2019/02/net-core/HttpClient-HttpClientFactory-InNetCore.html

参考:

未完待续...

相关推荐