请使用IHttpClientFactory代替直接创建HttpClient

作者 the7
发布于 2020年02月13日
评论 0
浏览 287

直接实例创建HttpClient,当然是可以。问题就出在,当遇到频繁访问的时候,会导致Socket耗尽。即便用using语法包一层,但在调用Dispose方法时,连接并不会立即释放,如果遇到频繁访问,依然存在Socket耗尽的问题,所以,微软推荐用IHttpClientFactory来创建HttpClient

基本使用

在启动方法中使用AddHttpClient来注册IHttpClientFactory

public void ConfigureServices(IServiceCollection services)
{
    services.AddHttpClient();

在需使用的地方

public class TestController:Controller
{
   private readonly IHttpClientFactory _httpClientFactory;
   public TestController(IHttpClientFactory httpClientFactory)
   {
      _httpClientFactory = httpClientFactory;
   }
   public IActionResult Home()
   {
      var client = _clientFactory.CreateClient();
	  ...
   }
}

命名化 HttpClient

有时候项目中可能会用到多个client,每个client也需要不同的配置,比如做爬虫你可能要带上Cookie信息,诸如此类的需求,这时候我们就可以使用命名化HttpClient。

services.AddHttpClient("github", c =>
{
    c.BaseAddress = new Uri("https://api.github.com/");
    // Github API versioning
    c.DefaultRequestHeaders.Add("Accept", "application/vnd.github.v3+json");
    // Github requires a user-agent
    c.DefaultRequestHeaders.Add("User-Agent", "HttpClientFactory-Sample");
});

在需使用的地方

public class TestController:Controller
{
   private readonly IHttpClientFactory _httpClientFactory;
   public TestController(IHttpClientFactory httpClientFactory)
   {
      _httpClientFactory = httpClientFactory;
   }
   public IActionResult Home()
   {
      var client = _clientFactory.CreateClient("github");
	  ...
   }
}

类型化 HttpClient

启动类中注册

services.AddHttpClient<TestService>();//普通注册

services.AddHttpClient<Test1Service>(c =>
{
    c.BaseAddress = new Uri("https://api.github.com/");
    c.DefaultRequestHeaders.Add("Accept", "application/vnd.github.v3+json");
    c.DefaultRequestHeaders.Add("User-Agent", "HttpClientFactory-Sample");
}); // 配置

在需要使用的地方

public class TestService
{
   private readonly HttpClient _httpClient;
   public TestService(HttpClient httpClient)
   {
      _httpClient = httpClient;
   }
   public IActionResult Home()
   {
      var client = _httpClient;
	  ...
   }
}

单例或静态使用

在stackoverflow上也看到,有人把 HttpClient 做成单例或直接设为静态字段的,其实我觉得也是可以的,微软官方文档上也写着

But there’s a second issue with HttpClient that you can have when you use it as singleton or static object. In this case, a singleton or static HttpClient doesn't respect DNS changes, as explained in this issue at the dotnet/corefx GitHub repository.

只是不能监测DNS变动,如果你能确保DNS不变,那么是可以用静态或单例的,个人觉得。

0条评论

请先登录后发表评论
提交评论
标签云
css (1) less calc (1) C# (4) C#进制转换 (1) asp.net core (8) Authentication (1) 注销 (1) 登录 (1) 验证 (1) scroll-view (1) 微信小程序 (4) 滚动到底部 (1) StackExchange.Redis (1) google (1) 百度 (1) nginx (2) 大文件 (2) 微信小程序c#解密 (1) 微信小程序获取手机号 (1) openid (1) session_key (1) CDN (1) URL鉴权 (1) 阿里云 (1) async (1) await (1) 禁止下拉上滑效果 (1) Index类型 (1) Range类型 (1) dontent publish (1) dotnet publish在线生成器 (1) System.DrawingCore.GDIPlus报错 (1) centos (1) 中文字体 (1) SqlBulkCopy (1) SqlSugar (1) JWT (5) 认证 (3) RSA JWT (1) 非对称加密 (1) 写信 (1) 见字如面 (1) 优化建议 (2) 正确操作字符串 (1) Java (1) JWT退出 (1) RefreshToken (1) .NET Core网站开发框架 (1) Moz (3) 墨子 (1) JSON.NET (1) Newtonsoft (1) System.Text.Json (1) 自定义后台路径 (1) .netcore (1) quartz (2) 作业调度框架 (1) 作业调度 (1) 定时任务 (1) exception (1) 异常处理 (1) HttpClient (1) IHttpClientFactory (1) RDM (1) Redis (1) Redis Desktop Manager (1) RedisDesktopManager (1) linux (1) mac (1) windows (1) Could not get any response (1) postman (1) leetcode (2) 力扣 (1) 回文字符串 (1) 面试刷题 (1) centos7 (1) php安装 (1) 网易云插件 (1) 马甲App (1) Discuz插件 (1) 网易云音乐 (1) Blazor (1) 五子棋 (1) c#解题 (1) 最长连续序列 (1) Swagger (1) 在线文档 (1) blob (1) mp4 (1) 视频 (1) big file (1) 上传 (1) s (1) Azure (1) Azure Key Vault (1) Configuration (1) 密钥保管库 (1) Dapper安装 (1) Dapper是什么 (1) Dapper连接Mysql (1) Dapper连接SqlServer (1) dapper (1)