【发布时间】:2019-02-08 17:13:08
【问题描述】:
我们可以在这里阅读YOU'RE USING HTTPCLIENT WRONG AND IT IS DESTABILIZING YOUR SOFTWARE,我们不应该为每个 http 请求创建和处置 HttpClient。相反,它应该被缓存和重用(例如作为 DI 容器中的 Singleton)。以及HttpClient 的官方 .NET 文档:
HttpClient 旨在被实例化一次并在应用程序的整个生命周期中重复使用。为每个请求实例化一个 HttpClient 类将耗尽重负载下可用的套接字数量。这将导致 SocketException 错误。下面是一个正确使用 HttpClient 的例子。
推荐使用HttpClientFactory,但是看了之后:
public interface IHttpClientFactory
{
/// <summary>
/// Creates and configures an <see cref="T:System.Net.Http.HttpClient" /> instance using the configuration that corresponds
/// to the logical name specified by <paramref name="name" />.
/// </summary>
/// <param name="name">The logical name of the client to create.</param>
/// <returns>A new <see cref="T:System.Net.Http.HttpClient" /> instance.</returns>
/// <remarks>
/// <para>
/// Each call to <see cref="M:System.Net.Http.IHttpClientFactory.CreateClient(System.String)" /> is guaranteed to return a new <see cref="T:System.Net.Http.HttpClient" />
/// instance. Callers may cache the returned <see cref="T:System.Net.Http.HttpClient" /> instance indefinitely or surround
/// its use in a <langword>using</langword> block to dispose it when desired.
/// </para>
/// <para>
/// The default <see cref="T:System.Net.Http.IHttpClientFactory" /> implementation may cache the underlying
/// <see cref="T:System.Net.Http.HttpMessageHandler" /> instances to improve performance.
/// </para>
/// <para>
/// Callers are also free to mutate the returned <see cref="T:System.Net.Http.HttpClient" /> instance's public properties
/// as desired.
/// </para>
/// </remarks>
HttpClient CreateClient(string name);
}
它说每次调用都会创建一个 HttpClient 实例,调用者可以缓存它。
保证每次调用 IHttpClientFactory.CreateClient 都会返回一个新的 HttpClient 实例。调用者可以无限期缓存返回的实例或包围 它在 using 块中的使用以在需要时对其进行处理。
所以问题是我应该完全依赖 HttpClientFactory 还是应该缓存创建的 HttpClient ?
在我们的项目中,我们每次发出请求时都会使用 HttpClientFactory.CreateClient,他仍然会遇到套接字异常。
【问题讨论】:
-
文档说它每次都会创建一个新实例,并且您知道应该使用单个实例...所以显然您应该缓存?我在这里错过了什么
-
@BradleyDotNET 有很多关于 HttpClientFactory 的文章,但没有人这么说。请理解我的惊愕。
-
@mardok 不,那是 HttpClientFactory 的工作
-
@BradleyDotNET 它是 HttpClientFactory 负责缓存和 刷新 实例。它的存在是为了让人们不必缓存
-
@mardok HttpClientFactory 缓存实际执行网络操作的 HttpMessageHandler。
标签: c# .net-core httpclient dotnet-httpclient