[英]Is it cheap to create brand new HttpClient per request
I always thought it's an antipattern since MS docs was always saying " HttpClient
is intended to be instantiated once per application, rather than per-use".我一直认为这是一种反模式,因为 MS 文档总是说“
HttpClient
旨在为每个应用程序实例化一次,而不是每次使用”。 But the more I dive into modern C# development the more I see things changed.但我越深入现代 C# 开发,我就越发现事情发生了变化。 For example here is a tweet about
IHttpClientFactory
例如这里是关于
IHttpClientFactory
的推文
A new HttpClient is created each time, but HttpClient is cheap to create.
每次都会创建一个新的 HttpClient,但 HttpClient 的创建成本很低。
The internal HTTP handler that the HttpClient uses to make the request (ie the part that does all the work and is expensive) is intelligently cached and reused by the factory.
HttpClient 用来发出请求的内部 HTTP 处理程序(即完成所有工作且成本高昂的部分)被工厂智能缓存和重用。
Which says if you reuse HttpMessageHandler
for multiple HttpClient
s you're golden.这说明如果您为多个
HttpClient
重用HttpMessageHandler
,那么您就是黄金。
Assume we want to set some headers for each HTTP request.假设我们要为每个 HTTP 请求设置一些标头。 Should we do it the old fashion way with
HttpRequestMessage
interceptors or could I just create a per-request HttpClient
and since I'm going to reuse the same HttpRequestMessage
I'm completely fine?我们应该使用
HttpRequestMessage
拦截器以旧的方式来做,还是我可以只创建一个每个请求的HttpClient
并且因为我要重用相同的HttpRequestMessage
我完全没问题? Is it the modern way to perform per-request message modifications?这是执行每个请求消息修改的现代方式吗?
HttpRequestMessage
is not intended to be reused. HttpRequestMessage
不打算被重用。 HttpClient
will actually modify the HttpRequestMessage
when sending your request, so it's not a good idea to use it afterward. HttpClient
在发送你的请求时实际上会修改HttpRequestMessage
,所以以后使用它不是一个好主意。
In general, use IHttpClientFactory
.通常,使用
IHttpClientFactory
。 It does more than just reusing a message handler, such as periodic recycling of connection pools.它不仅仅是重用消息处理程序,例如定期回收连接池。
One good use of creating multiple HttpClient
instances against a single message handler is if you want to set different default headers for calling multiple APIs against the same endpoint.针对单个消息处理程序创建多个
HttpClient
实例的一个很好的用途是,如果您想为针对同一端点调用多个 API 设置不同的默认标头。 This allows for pooling of connections to that endpoint without needing to set headers on each message.这允许汇集到该端点的连接,而无需在每条消息上设置标头。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.