DotNetCore深入了解之三HttpClientFactory类
当需要向某特定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 = ; 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 = ;
for (var i = ; 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 > )
{
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)
DotNetCore深入了解之三HttpClientFactory类的更多相关文章
- DotNetCore深入了解:HTTPClientFactory类
一.HttpClient使用 在C#中,如果我们需要向某特定的URL地址发送Http请求的时候,通常会用到HttpClient类.会将HttpClient包裹在using内部进行声明和初始化,如下面的 ...
- dotnetcore 与 hbase 之三——c# for hbase 客户端的使用
说明 在上一篇文章dotnetcore 与 hbase 之二--thrift 客户端的制作中已经可以找到 c# hbase 客户端的使用方法了,为什么这里单独列出一篇文章来讲述呢?最简单的理由就是,本 ...
- Java高效编程之三【类和接口】
本部分包含的一些指导原则,可以帮助哦我们更好滴利用这些语言元素,以便让设计出来的类更加有用.健壮和灵活. 十二.使类和成员的访问能力最小化 三个关键词访问修饰符:private(私有的=类级别的).未 ...
- 转:【深入Java虚拟机】之三:类初始化
转载请注明出处:http://blog.csdn.net/ns_code/article/details/17845821 类初始化是类加载过程的最后一个阶段,到初始化阶段,才真正开始执行类中的Jav ...
- DotNetCore深入了解之一Startup类
一个典型的ASP.NET Core应用程序会包含Program与Startup两个文件.Program类中有应用程序的入口方法Main,其中的处理逻辑通常是创建一个WebHostBuilder,再生成 ...
- 【深入Java虚拟机】之三:类初始化
类初始化是类加载过程的最后一个阶段,到初始化阶段,才真正开始执行类中的Java程序代码.虚拟机规范严格规定了有且只有四种情况必须立即对类进行初始化: 遇到new.getstatic.putstatic ...
- Java基础之三、类的特性和接口
类的派生.多态.抽象类.接口 1:派生-extends 派生就是继承已有类非私有的字段和方法等创建新的类,还可以添加.重写字段和方法: 在类的派生中,构造函数不可以被继承: 派生源的类-父类/基类/超 ...
- Asp.Net Core 轻松学-HttpClient的演进和避坑
前言 在 Asp.Net Core 1.0 时代,由于设计上的问题, HttpClient 给开发者带来了无尽的困扰,用 Asp.Net Core 开发团队的话来说就是:我们注意到,HttpC ...
- DotNetCore知识栈
#..NET Core提供的特性 1.开源.免费 2.轻量级.跨平台 3.组件化.模块化.IOC+Nuget.中间件 4.高性能 5.统一了MVC和WebAPI编程模型 a) 比如:ASP.NET ...
随机推荐
- bzoj 2653 middle 二分答案 主席树判定
判断中位数是否可行需要将当前的解作为分界,大于其的置为1,小于为-1,然后b-c必选,ab,cd可不选,这个用线段树判定就好 但不能每次跑,所以套主席树,按权值排序,构建主席树,更新时将上一个节点改为 ...
- BZOJ_4198_[Noi2015]荷马史诗_huffman实现
BZOJ_4198_[Noi2015]荷马史诗_huffman实现 题意: Allison 最近迷上了文学.她喜欢在一个慵懒的午后,细细地品上一杯卡布奇诺,静静地阅读她爱不释手的<荷马史诗> ...
- BZOJ_4892_[Tjoi2017]dna_哈希
BZOJ_4892_[Tjoi2017]dna_哈希 Description 加里敦大学的生物研究所,发现了决定人喜不喜欢吃藕的基因序列S,有这个序列的碱基序列就会表现出喜欢吃藕的 性状,但是研究人员 ...
- JLOI2018 划水中...
day -3:月考成绩刚刚出炉,嗯,还看得过去,为此,我决定脱产3天...花了一天时间,学习splay day -2:在某人(汤)的刺激下,决定用半天时间A掉去年省选D2T1,事实证明,我还是图样图森 ...
- Linux vim常用命令
什么是 vim? Vim是从 vi 发展出来的一个文本编辑器.代码补完.编译及错误跳转等方便编程的功能特别丰富,在程序员中被广泛使用. 简单的来说, vi 是老式的字处理器,不过功能已经很齐全了,但是 ...
- Python数据结构应用5——排序(Sorting)
在具体算法之前,首先来看一下排序算法衡量的标准: 比较:比较两个数的大小的次数所花费的时间. 交换:当发现某个数不在适当的位置时,将其交换到合适位置花费的时间. 冒泡排序(Bubble Sort) 这 ...
- 基于 Maven 的多模块 Java ( Spring ) 项目构建
索引: 开源Spring解决方案--lm.solution 参看代码 GitHub: solution/pom.xml pojo/pom.xml mapper/pom.xml common/pom.x ...
- Robot Framework 源码解析(1) - java入口点
一直很好奇Robot Framework 是如何通过关键字驱动进行测试的,好奇它是如何支持那么多库的,好奇它是如何完成截图的.所以就打算研究一下它的源码. 这是官方给出的Robot framework ...
- 《前端之路》之 Babel 下一代 JavaScript 语法编译器
写本章的内容的出发点主要是 为了对于之前关于 JS 版本的一个总结,在之前的开发中,我们始终对于 ECMAScript 的版本的更新不够重视,以至于在后面的 开发过程中,我们始终会被各种新奇的语法打断 ...
- 别开心太早,Python 官方文档的翻译差远了
近几天,很多公众号发布了 Python 官方文档的消息.然而,一个特别奇怪的现象就发生了,让人啼笑皆非. Python 文档的中文翻译工作一直是“默默无闻”,几个月前,我还吐槽过这件事<再聊聊P ...