侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

DotNetCore深入了解之HttpClientFactory类详解

技术  /  管理员 发布于 7年前   227

当需要向某特定URL地址发送HTTP请求并得到相应响应时,通常会用到HttpClient类。该类包含了众多有用的方法,可以满足绝大多数的需求。但是如果对其使用不当时,可能会出现意想不到的事情。

using(var client = new HttpClient())

对象所占用资源应该确保及时被释放掉,但是,对于网络连接而言,这是错误的。

原因有二,网络连接是需要耗费一定时间的,频繁开启与关闭连接,性能会受影响;再者,开启网络连接时会占用底层socket资源,但在HttpClient调用其本身的Dispose方法时,并不能立刻释放该资源,这意味着你的程序可能会因为耗尽连接资源而产生预期之外的异常。

所以比较好的解决方法是延长HttpClient对象的使用寿命,比如对其建一个静态的对象:

private static HttpClient Client = new HttpClient();

但从程序员的角度来看,这样的代码或许不够优雅。

所以在.NET Core 2.1中引入了新的HttpClientFactory类。

它的用法很简单,首先是对其进行IoC的注册:

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

然后通过IHttpClientFactory创建一个HttpClient对象,之后的操作如旧,但不需要担心其内部资源的释放:

public class LzzDemoController : Controller{ IHttpClientFactory _httpClientFactory; public LzzDemoController(IHttpClientFactory httpClientFactory) {  _httpClientFactory = httpClientFactory; } public IActionResult Index() {  var client = _httpClientFactory.CreateClient();  var result = client.GetStringAsync("http://myurl/");  return View(); }}

AddHttpClient的源码:

public static IServiceCollection AddHttpClient(this IServiceCollection services){ if (services == null) {  throw new ArgumentNullException(nameof(services)); } services.AddLogging(); services.AddOptions(); // // Core abstractions // services.TryAddTransient<HttpMessageHandlerBuilder, DefaultHttpMessageHandlerBuilder>(); services.TryAddSingleton<IHttpClientFactory, DefaultHttpClientFactory>(); // // Typed Clients // services.TryAdd(ServiceDescriptor.Singleton(typeof(ITypedHttpClientFactory<>), typeof(DefaultTypedHttpClientFactory<>))); // // Misc infrastructure // services.TryAddEnumerable(ServiceDescriptor.Singleton<IHttpMessageHandlerBuilderFilter, LoggingHttpMessageHandlerBuilderFilter>()); return services;}

它的内部为IHttpClientFactory接口绑定了DefaultHttpClientFactory类。

再看IHttpClientFactory接口中关键的CreateClient方法:

public HttpClient CreateClient(string name){ if (name == null) {  throw new ArgumentNullException(nameof(name)); } var entry = _activeHandlers.GetOrAdd(name, _entryFactory).Value; var client = new HttpClient(entry.Handler, disposeHandler: false); StartHandlerEntryTimer(entry); var options = _optionsMonitor.Get(name); for (var i = 0; i < options.HttpClientActions.Count; i++) {  options.HttpClientActions[i](client); } return client;}

HttpClient的创建不再是简单的new HttpClient(),而是传入了两个参数:HttpMessageHandler handler与bool disposeHandler。disposeHandler参数为false值时表示要重用内部的handler对象。handler参数则从上一句的代码可以看出是以name为键值从一字典中取出,又因为DefaultHttpClientFactory类是通过TryAddSingleton方法注册的,也就意味着其为单例,那么这个内部字典便是唯一的,每个键值对应的ActiveHandlerTrackingEntry对象也是唯一,该对象内部中包含着handler。

下一句代码StartHandlerEntryTimer(entry); 开启了ActiveHandlerTrackingEntry对象的过期计时处理。默认过期时间是2分钟。

internal void ExpiryTimer_Tick(object state){ var active = (ActiveHandlerTrackingEntry)state; // The timer callback should be the only one removing from the active collection. If we can't find // our entry in the collection, then this is a bug. var removed = _activeHandlers.TryRemove(active.Name, out var found); Debug.Assert(removed, "Entry not found. We should always be able to remove the entry"); Debug.Assert(object.ReferenceEquals(active, found.Value), "Different entry found. The entry should not have been replaced"); // At this point the handler is no longer 'active' and will not be handed out to any new clients. // However we haven't dropped our strong reference to the handler, so we can't yet determine if // there are still any other outstanding references (we know there is at least one). // // We use a different state object to track expired handlers. This allows any other thread that acquired // the 'active' entry to use it without safety problems. var expired = new ExpiredHandlerTrackingEntry(active); _expiredHandlers.Enqueue(expired); Log.HandlerExpired(_logger, active.Name, active.Lifetime); StartCleanupTimer();}

先是将ActiveHandlerTrackingEntry对象传入新的ExpiredHandlerTrackingEntry对象。

public ExpiredHandlerTrackingEntry(ActiveHandlerTrackingEntry other){ Name = other.Name; _livenessTracker = new WeakReference(other.Handler); InnerHandler = other.Handler.InnerHandler;}

在其构造方法内部,handler对象通过弱引用方式关联着,不会影响其被GC释放。

然后新建的ExpiredHandlerTrackingEntry对象被放入专用的队列。

最后开始清理工作,定时器的时间间隔设定为每10秒一次。

internal void CleanupTimer_Tick(object state){ // Stop any pending timers, we'll restart the timer if there's anything left to process after cleanup. // // With the scheme we're using it's possible we could end up with some redundant cleanup operations. // This is expected and fine. //  // An alternative would be to take a lock during the whole cleanup process. This isn't ideal because it // would result in threads executing ExpiryTimer_Tick as they would need to block on cleanup to figure out // whether we need to start the timer. StopCleanupTimer(); try {  if (!Monitor.TryEnter(_cleanupActiveLock))  {   // We don't want to run a concurrent cleanup cycle. This can happen if the cleanup cycle takes   // a long time for some reason. Since we're running user code inside Dispose, it's definitely   // possible.   //   // If we end up in that position, just make sure the timer gets started again. It should be cheap   // to run a 'no-op' cleanup.   StartCleanupTimer();   return;  }  var initialCount = _expiredHandlers.Count;  Log.CleanupCycleStart(_logger, initialCount);  var stopwatch = ValueStopwatch.StartNew();  var disposedCount = 0;  for (var i = 0; i < initialCount; i++)  {   // Since we're the only one removing from _expired, TryDequeue must always succeed.   _expiredHandlers.TryDequeue(out var entry);   Debug.Assert(entry != null, "Entry was null, we should always get an entry back from TryDequeue");   if (entry.CanDispose)   {    try    {     entry.InnerHandler.Dispose();     disposedCount++;    }    catch (Exception ex)    {     Log.CleanupItemFailed(_logger, entry.Name, ex);    }   }   else   {    // If the entry is still live, put it back in the queue so we can process it     // during the next cleanup cycle.    _expiredHandlers.Enqueue(entry);   }  }  Log.CleanupCycleEnd(_logger, stopwatch.GetElapsedTime(), disposedCount, _expiredHandlers.Count); } finally {  Monitor.Exit(_cleanupActiveLock); } // We didn't totally empty the cleanup queue, try again later. if (_expiredHandlers.Count > 0) {  StartCleanupTimer(); }}

上述方法核心是判断是否handler对象已经被GC,如果是的话,则释放其内部资源,即网络连接。

回到最初创建HttpClient的代码,会发现并没有传入任何name参数值。这是得益于HttpClientFactoryExtensions类的扩展方法。

public static HttpClient CreateClient(this IHttpClientFactory factory){ if (factory == null) {  throw new ArgumentNullException(nameof(factory)); } return factory.CreateClient(Options.DefaultName);}

Options.DefaultName的值为string.Empty。

DefaultHttpClientFactory缺少无参数的构造方法,唯一的构造方法需要传入多个参数,这也意味着构建它时需要依赖其它一些类,所以目前只适用于在ASP.NET程序中使用,还无法应用到诸如控制台一类的程序,希望之后官方能够对其继续增强,使得应用范围变得更广。

 public DefaultHttpClientFactory(  IServiceProvider services,  ILoggerFactory loggerFactory,  IOptionsMonitor<HttpClientFactoryOptions> optionsMonitor,  IEnumerable<IHttpMessageHandlerBuilderFilter> filters)

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对AIDI的支持。


  • 上一条:
    SignalR中丰富多彩的消息推送方式的实现代码
    下一条:
    VS+opencv实现鼠标移动图片
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 2024.07.09日OpenAI将终止对中国等国家和地区API服务(0个评论)
    • 2024/6/9最新免费公益节点SSR/V2ray/Shadowrocket/Clash节点分享|科学上网|免费梯子(0个评论)
    • 国外服务器实现api.openai.com反代nginx配置(0个评论)
    • 2024/4/28最新免费公益节点SSR/V2ray/Shadowrocket/Clash节点分享|科学上网|免费梯子(0个评论)
    • 近期文章
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • Laravel 11.15版本发布 - Eloquent Builder中添加的泛型(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2017-07
    • 2017-08
    • 2017-09
    • 2018-01
    • 2018-07
    • 2018-08
    • 2018-09
    • 2018-12
    • 2019-01
    • 2019-02
    • 2019-03
    • 2019-04
    • 2019-05
    • 2019-06
    • 2019-07
    • 2019-08
    • 2019-09
    • 2019-10
    • 2019-11
    • 2019-12
    • 2020-01
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-08
    • 2020-09
    • 2020-10
    • 2020-11
    • 2021-04
    • 2021-05
    • 2021-06
    • 2021-07
    • 2021-08
    • 2021-09
    • 2021-10
    • 2021-12
    • 2022-01
    • 2022-02
    • 2022-03
    • 2022-04
    • 2022-05
    • 2022-06
    • 2022-07
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-02
    • 2023-03
    • 2023-04
    • 2023-05
    • 2023-06
    • 2023-07
    • 2023-08
    • 2023-09
    • 2023-10
    • 2023-12
    • 2024-02
    • 2024-04
    • 2024-05
    • 2024-06
    • 2025-02
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客