.net core 中使用httpclient,HttpClientFactory的问题

Microsoft 在.Net Framework 4.5中引入了HttpClient,并且是在.NET服务器端代码中使用Web API的最常用方法。但它有一些严重的问题,如释放HttpClient对象不立即关闭套接字,太多实例影响性能和单个的HttpClient或共享HttpClient实例不尊重DNS生存时间(TTL)设置。当并没有大批量或者并发调用时,选择 HttpClient 还行:

 private static readonly HttpClient HttpClient = new HttpClient();//定义




 var res = await HttpClient.GetStringAsync(url);//调用

 .net core 2.1 引入了HttpClientFactory的一些问题,当高并发时可以使用HttpClientFactory,例子链接里有,我只介绍一个在类库中使用方法:

1.类库中建封装类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;

namespace Oss.Utils
{
    public class HttpClientFactory
    {
        public HttpClient Client { get; private set; }

        public HttpClientFactory(HttpClient httpClient)
        {

                           httpClient.BaseAddress = new Uri("https://api.github.com/");
                          httpClient.DefaultRequestHeaders.Add("Accept", "application/vnd.github.v3+json");
                          httpClient.DefaultRequestHeaders.Add("User-Agent", "HttpClientFactory-Sample");
                          httpClient.Timeout = TimeSpan.FromSeconds(60);
                         Client = httpClient;

        }
    }
}

2.其他类中调用就好了:

  private static readonly HttpClient HttpClient = new HttpClient();
  private static readonly HttpClientFactory HttpClientFactory = new HttpClientFactory(HttpClient);
...
...
...


var res = await HttpClientFactory.Client.GetStringAsync(url);

okay,调用完成。

说明一下:在.net core 项目中使用HttpClientFactory的时候,要是在Startup.cs注册时,要安装:

Microsoft.Extensions.Http   nuget包,

直接搜索即可。

具体使用方法和参考链接如下:https://www.cjavapy.com/article/150/

posted @ 2018-12-20 17:03  翱翔的小鱼  阅读(3939)  评论(0编辑  收藏  举报