我应该创建几个HttpClient? [英] How many HttpClients should I create?

查看:161
本文介绍了我应该创建几个HttpClient?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最初,我的代码在每个请求的using语句中创建了一个新的HttpClient。然后,我阅读了几篇有关重用HttpClient来提高性能的文章。

Originally my code created a new HttpClient in a using statement on every request. Then I read several articles about reusing HttpClient to increase performance.

以下是其中一篇文章的摘录:

Here is an excerpt from one such article:


我不建议在Using块内创建HttpClient来进行
单个请求。处置HttpClient时,也会导致基础
连接也关闭。这意味着下一个请求必须
重新打开该连接。您应该尝试重新使用HttpClient
实例。

I do not recommend creating a HttpClient inside a Using block to make a single request. When HttpClient is disposed it causes the underlying connection to be closed also. This means the next request has to re-open that connection. You should try and re-use your HttpClient instances.

http://www.bizcoder.com/httpclient-it-lives-and-it-is-glorious

在我看来,仅当连续有多个请求到达同一位置(例如www.api1.com)时,保持连接打开才有用。

It seems to me that leaving a connection open is only going to be useful if multiple requests in a row go to the same places - such as www.api1.com.

我的问题是,我应该如何创建HttpClient?

My question is, how may HttpClients should I create?

我的网站与10种不同的服务有关后端。

My website talks to about ten different services on the back end.

我应该为所有这些对象创建一个单一的HttpClient还是为后端使用的每个域创建一个单独的HttpClient?

Should I create a single HttpClient for all of them to consume, or should I create a separate HttpClient per domain that I use on the back end?

示例:
如果我访问www.api1.com和www.api2.com,我应该创建2个不同的HttpClient,还是仅创建一个HttpClient?

Example: If I talk to www.api1.com and www.api2.com, should I create 2 distinct HttpClients, or only a single HttpClient?

推荐答案

实际上,处置HttpClient不会强制关闭连接池中的基础TCP / IP连接。最佳性能方案是您所建议的:

Indeed, Disposing of HttpClient will not forcibly close the underlying TCP/IP connection from the connection pool. Your best performance scenario is what you have suggested:


  • 为需要的每个后端服务保持HttpClient实例为活动状态连接到应用程序或应用程序的生命周期。

  • Keep an instance of HttpClient alive for each back-end service you need to connect to or the lifetime of your application.

根据后端服务的详细信息,您可能还希望每个客户端都有一个客户端后端服务上的独特API。 (同一域中的API可能会在各处路由。)

Depending on the details you have about the back-end service, you may also want to have a client for each distinct API on that back-end service as well. (API's in the same domain could be routing all over the place.)

这篇关于我应该创建几个HttpClient?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆