DotNetCore深入了解:HTTPClientFactory类
一、HttpClient使用
在C#中,如果我们需要向某特定的URL地址发送Http请求的时候,通常会用到HttpClient类。会将HttpClient包裹在using内部进行声明和初始化,如下面的代码:
using (var httpClient = new HttpClient())
{
// 逻辑处理代码
}
HttpClient类包含了许多有用的方法,使用上面的代码,可以满足绝大多数的需求,但是如果对其使用不当时,可能会出现意想不到的事情。
上面代码的技术范点:当你使用继承了IDisposable接口的对象时,建议在using代码块中声明和初始化,当using代码段执行完成后,会自动释放该对象而不需要手动进行显示Dispose操作。
对象所占用资源应该确保及时被释放掉,但是,对于网络连接而言,这是错误的。具体原因有下面两点:
- 网络连接是需要耗费一定时间的,频繁开启与关闭连接,性能会受到影响。
- 开启网络连接时会占用低层socket资源,但在HttpClient调用其本身的Dispose方法时,并不能立即释放该资源,这意味着你的程序可能会因为耗尽连接资源而产生预期之外的异常。
看下面一段代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks; namespace HttpClientDemo
{
class Program
{
static void Main(string[] args)
{
//using (var httpClient = new HttpClient())
//{
// // 逻辑处理代码
//} HttpAsync();
Console.WriteLine("Hello World!");
Console.Read(); } public static async void HttpAsync()
{
for (int i = 0; i < 10; i++)
{
using (var client = new HttpClient())
{
var result = await client.GetAsync("http://www.baidu.com");
Console.WriteLine($"{i}:{result.StatusCode}");
}
}
}
}
}
运行项目输出结果后,通过netstate查看下TCP连接情况,会发现连接依然存在,状态为“TIME_WAIT”(继续等待看是否还有延迟的包会传输过来)。
这里就会出现一个坑:在高并发的情况下,连接来不及释放,socket连接被耗尽,耗尽之后就会出现错误。就是会出现“各种套接字问题”。
那么如何解决这个问题呢?比较好的解决方法是延长HttpClient对象的使用寿命,实现HttpClient对象的复用,比如对其建一个静态的对象:
private static HttpClient Client = new HttpClient();
我们使用这种方式优化上面的代码
using System;
using System.Net.Http; namespace HttpClientDemo
{
class Program
{
private static readonly HttpClient _client = new HttpClient();
static void Main(string[] args)
{
HttpAsync();
Console.WriteLine("Hello World");
Console.ReadKey();
} public static async void HttpAsync()
{
for (int i = 0; i < 10; i++)
{
var result = await _client.GetAsync("http://www.baidu.com");
Console.WriteLine($"{i}:{result.StatusCode}");
}
} }
}
这样调整HttpClient的引用后,虽然可以解决一些问题,但是仍然存在一些问题:
- 因为是复用的HttpClient,那么一些公共的设置就没办法灵活的调整,如请求头的自定义。
- 因为HttpClient请求每个url时,会缓存url对应的主机ip,从而会导致DNS更新失效。
为了解决这些问题,在.NET Core 2.1中引入了新的HttpClientFactory类。
二、HttpClientFactory使用
微软在.NET Core 2.1中新引入了HttpClientFactory类,具有如下的优势:
- HttpClientFactory很高效,可以最大程度上节省系统的sock而。
- Factory,顾名思义HttpClientfactory就是HttpClient的工厂,内部已经帮我们处理好了对HttpClient的管理,不需要我们人工进行对象释放,同时,支持自定义请求头、支持DNS更新等。
我们用一个ASP.NET Core的程序作为示例,它的用法非常简单,首先是对其进行IOC注册:
public void ConfigureServices(IServiceCollection services)
{
// 注入HttpClient
services.AddHttpClient("client_1", config => //这里指定的name=client_1,可以方便我们后期服用该实例
{
config.BaseAddress = new Uri("http://www.baidu.com");
config.DefaultRequestHeaders.Add("header_1", "header_1");
});
services.AddHttpClient("client_2", config =>
{
config.BaseAddress = new Uri("https://www.qq.com/");
config.DefaultRequestHeaders.Add("header_2", "header_2");
});
services.AddHttpClient();
services.AddControllers();
}
然后在控制器里面通过IHttpClientFactory创建一个HttpClient对象,之后的操作跟以前一样,但不需要担心其内部资源的释放:
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc; namespace HttpClientFactoryDemo.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class DemoController : ControllerBase
{
IHttpClientFactory _httpClientFactory; /// <summary>
/// 通过构造函数实现注入
/// </summary>
/// <param name="httpClientFactory"></param>
public DemoController(IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
} public async Task<string> Get()
{
var client = _httpClientFactory.CreateClient("client_1"); //复用在Startup中定义的client_1的httpclient
var result = await client.GetStringAsync("/page1.html"); var client2 = _httpClientFactory.CreateClient(); //新建一个HttpClient
var result2 = await client.GetAsync("http://www.baidu.com"); return result2.StatusCode.ToString();
}
}
}
程序运行结果:


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;
}
看下面这句代码:
services.TryAddSingleton<IHttpClientFactory, DefaultHttpClientFactory>();
这里添加依赖注入的时候为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。
参考:https://blog.csdn.net/weixin_34321753/article/details/91362881
https://www.cnblogs.com/lizhizhang/p/9502862.html
DotNetCore深入了解:HTTPClientFactory类的更多相关文章
- DotNetCore深入了解之三HttpClientFactory类
当需要向某特定URL地址发送HTTP请求并得到相应响应时,通常会用到HttpClient类.该类包含了众多有用的方法,可以满足绝大多数的需求.但是如果对其使用不当时,可能会出现意想不到的事情. usi ...
- DotNetCore知识栈
#..NET Core提供的特性 1.开源.免费 2.轻量级.跨平台 3.组件化.模块化.IOC+Nuget.中间件 4.高性能 5.统一了MVC和WebAPI编程模型 a) 比如:ASP.NET ...
- .NET Core开发日志——HttpClientFactory
当需要向某特定URL地址发送HTTP请求并得到相应响应时,通常会用到HttpClient类.该类包含了众多有用的方法,可以满足绝大多数的需求.但是如果对其使用不当时,可能会出现意想不到的事情. 博客园 ...
- Java类的继承与多态特性-入门笔记
相信对于继承和多态的概念性我就不在怎么解释啦!不管你是.Net还是Java面向对象编程都是比不缺少一堂课~~Net如此Java亦也有同样的思想成分包含其中. 继承,多态,封装是Java面向对象的3大特 ...
- Asp.Net Core 轻松学-HttpClient的演进和避坑
前言 在 Asp.Net Core 1.0 时代,由于设计上的问题, HttpClient 给开发者带来了无尽的困扰,用 Asp.Net Core 开发团队的话来说就是:我们注意到,HttpC ...
- .NET Core 学习资料精选:入门
开源跨平台的.NET Core,还没上车的赶紧的,来不及解释了-- 本系列文章,主要分享一些.NET Core比较优秀的社区资料和微软官方资料.我进行了知识点归类,让大家可以更清晰的学习.NET Co ...
- 《IT蓝豹》挑战独立开发项目能力
做了5年的android开发,今天没事写写刚入行不久的时候第一次独立开发项目的心得体会, 当时我刚工作8个月,由于公司运营不善倒闭了,在2011年3月份我开始准备跳槽, 看了一周andro ...
- python爬虫抓网页的总结
python爬虫抓网页的总结 更多 python 爬虫 学用python也有3个多月了,用得最多的还是各类爬虫脚本:写过抓代理本机验证的脚本,写过在discuz论坛中自动登录自动发贴的脚本,写过自 ...
- 爬虫总结_python
import sqlite3 Python 的一个非常大的优点是很容易写很容易跑起来,缺点就是很多不那么著名的(甚至一些著名的)程序和库都不像 C 和 C++ 那边那样专业.可靠(当然这也有动态类型 ...
随机推荐
- (精)题解 guP4878 [USACO05DEC] 布局
差分约束模版题 不过后三个点简直是满满的恶意qwq 这里不说做题思路(毕竟纯模板),只说几个坑点: 1. 相邻的两头牛间必须建边(这点好像luogu没有体现),例如一组数据: 4 1 1 1 4 10 ...
- 手把手0基础Centos下安装与部署paddleOcr 教程
!!!以下内容为作者原创,首发于个人博客园&掘金平台.未经原作者同意与许可,任何人.任何组织不得以任何形式转载.原创不易,如果对您的问题提供了些许帮助,希望得到您的点赞支持. 0.paddle ...
- 【论文阅读】PRM-RL Long-range Robotic Navigation Tasks by Combining Reinforcement Learning and Sampling-based Planning
目录 摘要部分: I. Introduction II. Related Work III. Method **IMPORTANT PART A. RL agent training [第一步] B. ...
- PAT乙级:1057 数零壹 (20分)
PAT乙级:1057 数零壹 (20分) 题干 给定一串长度不超过 105 的字符串,本题要求你将其中所有英文字母的序号(字母 a-z 对应序号 1-26,不分大小写)相加,得到整数 N,然后再分析一 ...
- 完整的URL是怎样的?
完整的URL字段解读: URL:http://localhost:80/MzyPractice/chapter10/testb.php?name=Mei&radio=Test#dowel ht ...
- 基于小熊派Hi3861鸿蒙开发的IoT物联网学习【三】
软件定时器:是基于系统Tick时钟中断且由软件来模拟的定时器,当经过设定的Tick时钟计数值后会触发用户定义的回调函数.定时精度与系统Tick时钟的周期有关. 定时器运行机制: cmsis_os2的A ...
- 第十三天 -- 如何用U盘重装系统Win10以及如何用VMware12安装Win10
U盘制作启动盘 1.在电脑上插入U盘,关闭安全软件杀毒工具,然后打开装机吧U盘启动盘制作工具 2.选择刚插入的U盘,勾选上,点击一键制作启动U盘,制作前U盘数据必须转移备份: 3.选择格式化U盘,记得 ...
- Skywalking-04:扩展Metric监控信息
扩展 Metric 监控信息 官方文档 Source and Scope extension for new metrics 案例:JVM Thread 增加 Metrics 修改 Thread 的定 ...
- SQL SERVER 雨量计累计雨量(小时)的统计思路
PLC中定时读取5分钟雨量值,如何将该值统计为小时雨量作为累计?在sql server group by聚合函数,轻松实现该目的. 1.编写思路 数据库中字段依据datetime每五分钟插入一条语句, ...
- SpringBoot AOP中JoinPoint的用法和通知切点表达式
前言 上一篇文章讲解了springboot aop 初步完整的使用和整合 这一篇讲解他的接口方法和类 JoinPoint和ProceedingJoinPoint对象 JoinPoint对象封装了Spr ...