DotNetCore深入了解之HttpClientFactory类详解
当需要向某特定URL地址发送HTTP请求并得到相应响应时,通常会用到HttpClient类。该类包含了众多有用的方法,可以满足绝大多数的需求。但是如果对其使用不当时,可能会出现意想不到的事情。
using(varclient=newHttpClient())
对象所占用资源应该确保及时被释放掉,但是,对于网络连接而言,这是错误的。
原因有二,网络连接是需要耗费一定时间的,频繁开启与关闭连接,性能会受影响;再者,开启网络连接时会占用底层socket资源,但在HttpClient调用其本身的Dispose方法时,并不能立刻释放该资源,这意味着你的程序可能会因为耗尽连接资源而产生预期之外的异常。
所以比较好的解决方法是延长HttpClient对象的使用寿命,比如对其建一个静态的对象:
privatestaticHttpClientClient=newHttpClient();
但从程序员的角度来看,这样的代码或许不够优雅。
所以在.NETCore2.1中引入了新的HttpClientFactory类。
它的用法很简单,首先是对其进行IoC的注册:
publicvoidConfigureServices(IServiceCollectionservices)
{
services.AddHttpClient();
services.AddMvc();
}
然后通过IHttpClientFactory创建一个HttpClient对象,之后的操作如旧,但不需要担心其内部资源的释放:
publicclassLzzDemoController:Controller
{
IHttpClientFactory_httpClientFactory;
publicLzzDemoController(IHttpClientFactoryhttpClientFactory)
{
_httpClientFactory=httpClientFactory;
}
publicIActionResultIndex()
{
varclient=_httpClientFactory.CreateClient();
varresult=client.GetStringAsync("http://myurl/");
returnView();
}
}
AddHttpClient的源码:
publicstaticIServiceCollectionAddHttpClient(thisIServiceCollectionservices)
{
if(services==null)
{
thrownewArgumentNullException(nameof(services));
}
services.AddLogging();
services.AddOptions();
//
//Coreabstractions
//
services.TryAddTransient();
services.TryAddSingleton();
//
//TypedClients
//
services.TryAdd(ServiceDescriptor.Singleton(typeof(ITypedHttpClientFactory<>),typeof(DefaultTypedHttpClientFactory<>)));
//
//Miscinfrastructure
//
services.TryAddEnumerable(ServiceDescriptor.Singleton());
returnservices;
}
它的内部为IHttpClientFactory接口绑定了DefaultHttpClientFactory类。
再看IHttpClientFactory接口中关键的CreateClient方法:
publicHttpClientCreateClient(stringname)
{
if(name==null)
{
thrownewArgumentNullException(nameof(name));
}
varentry=_activeHandlers.GetOrAdd(name,_entryFactory).Value;
varclient=newHttpClient(entry.Handler,disposeHandler:false);
StartHandlerEntryTimer(entry);
varoptions=_optionsMonitor.Get(name);
for(vari=0;i
HttpClient的创建不再是简单的newHttpClient(),而是传入了两个参数:HttpMessageHandlerhandler与booldisposeHandler。disposeHandler参数为false值时表示要重用内部的handler对象。handler参数则从上一句的代码可以看出是以name为键值从一字典中取出,又因为DefaultHttpClientFactory类是通过TryAddSingleton方法注册的,也就意味着其为单例,那么这个内部字典便是唯一的,每个键值对应的ActiveHandlerTrackingEntry对象也是唯一,该对象内部中包含着handler。
下一句代码StartHandlerEntryTimer(entry);开启了ActiveHandlerTrackingEntry对象的过期计时处理。默认过期时间是2分钟。
internalvoidExpiryTimer_Tick(objectstate)
{
varactive=(ActiveHandlerTrackingEntry)state;
//Thetimercallbackshouldbetheonlyoneremovingfromtheactivecollection.Ifwecan'tfind
//ourentryinthecollection,thenthisisabug.
varremoved=_activeHandlers.TryRemove(active.Name,outvarfound);
Debug.Assert(removed,"Entrynotfound.Weshouldalwaysbeabletoremovetheentry");
Debug.Assert(object.ReferenceEquals(active,found.Value),"Differententryfound.Theentryshouldnothavebeenreplaced");
//Atthispointthehandlerisnolonger'active'andwillnotbehandedouttoanynewclients.
//Howeverwehaven'tdroppedourstrongreferencetothehandler,sowecan'tyetdetermineif
//therearestillanyotheroutstandingreferences(weknowthereisatleastone).
//
//Weuseadifferentstateobjecttotrackexpiredhandlers.Thisallowsanyotherthreadthatacquired
//the'active'entrytouseitwithoutsafetyproblems.
varexpired=newExpiredHandlerTrackingEntry(active);
_expiredHandlers.Enqueue(expired);
Log.HandlerExpired(_logger,active.Name,active.Lifetime);
StartCleanupTimer();
}
先是将ActiveHandlerTrackingEntry对象传入新的ExpiredHandlerTrackingEntry对象。
publicExpiredHandlerTrackingEntry(ActiveHandlerTrackingEntryother)
{
Name=other.Name;
_livenessTracker=newWeakReference(other.Handler);
InnerHandler=other.Handler.InnerHandler;
}
在其构造方法内部,handler对象通过弱引用方式关联着,不会影响其被GC释放。
然后新建的ExpiredHandlerTrackingEntry对象被放入专用的队列。
最后开始清理工作,定时器的时间间隔设定为每10秒一次。
internalvoidCleanupTimer_Tick(objectstate)
{
//Stopanypendingtimers,we'llrestartthetimerifthere'sanythinglefttoprocessaftercleanup.
//
//Withtheschemewe'reusingit'spossiblewecouldendupwithsomeredundantcleanupoperations.
//Thisisexpectedandfine.
//
//Analternativewouldbetotakealockduringthewholecleanupprocess.Thisisn'tidealbecauseit
//wouldresultinthreadsexecutingExpiryTimer_Tickastheywouldneedtoblockoncleanuptofigureout
//whetherweneedtostartthetimer.
StopCleanupTimer();
try
{
if(!Monitor.TryEnter(_cleanupActiveLock))
{
//Wedon'twanttorunaconcurrentcleanupcycle.Thiscanhappenifthecleanupcycletakes
//alongtimeforsomereason.Sincewe'rerunningusercodeinsideDispose,it'sdefinitely
//possible.
//
//Ifweendupinthatposition,justmakesurethetimergetsstartedagain.Itshouldbecheap
//toruna'no-op'cleanup.
StartCleanupTimer();
return;
}
varinitialCount=_expiredHandlers.Count;
Log.CleanupCycleStart(_logger,initialCount);
varstopwatch=ValueStopwatch.StartNew();
vardisposedCount=0;
for(vari=0;i0)
{
StartCleanupTimer();
}
}
上述方法核心是判断是否handler对象已经被GC,如果是的话,则释放其内部资源,即网络连接。
回到最初创建HttpClient的代码,会发现并没有传入任何name参数值。这是得益于HttpClientFactoryExtensions类的扩展方法。
publicstaticHttpClientCreateClient(thisIHttpClientFactoryfactory)
{
if(factory==null)
{
thrownewArgumentNullException(nameof(factory));
}
returnfactory.CreateClient(Options.DefaultName);
}
Options.DefaultName的值为string.Empty。
DefaultHttpClientFactory缺少无参数的构造方法,唯一的构造方法需要传入多个参数,这也意味着构建它时需要依赖其它一些类,所以目前只适用于在ASP.NET程序中使用,还无法应用到诸如控制台一类的程序,希望之后官方能够对其继续增强,使得应用范围变得更广。
publicDefaultHttpClientFactory(
IServiceProviderservices,
ILoggerFactoryloggerFactory,
IOptionsMonitoroptionsMonitor,
IEnumerablefilters)
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对毛票票的支持。