前言
官方文檔對 HttpClientHandler.MaxConnectionsPerServer 屬性有如下說明:
獲取或設置使用 HttpClient 對象發出請求時允許的最大并發連接數(每個服務器終結點)。請注意,該限制針對每個服務器終結點,例如,值為 256 表示允許 256 個到 http://www.adatum.com/ 的并發連接,以及另外 256 個到 http://www.adventure-works.com/ 的并發連接。
有網友在交流群中詢問,終結點到底指的啥,怎么判斷是同一終結點?
讓我們通過源碼來看看吧!
源碼分析
HttpClientHandler.MaxConnectionsPerServer
HttpClientHandler.MaxConnectionsPerServer 的實現代碼如下:
public?int?MaxConnectionsPerServer
{get?=>?_underlyingHandler.MaxConnectionsPerServer;set?=>?_underlyingHandler.MaxConnectionsPerServer?=?value;
}
實際使用的是_underlyingHandler.MaxConnectionsPerServer
。而_underlyingHandler
是SocketsHttpHandler
類的實例:
using?HttpHandlerType?=?System.Net.Http.SocketsHttpHandler;private?readonly?HttpHandlerType?_underlyingHandler;
SocketsHttpHandler.MaxConnectionsPerServer
SocketsHttpHandler.MaxConnectionsPerServer 的實現代碼如下:
public?int?MaxConnectionsPerServer
{get?=>?_settings._maxConnectionsPerServer;set{..._settings._maxConnectionsPerServer?=?value;}
}
實際使用的是_settings._maxConnectionsPerServer
。那么,誰在使用這個設置值呢?
HttpConnectionPool
我們定位到了HttpConnectionPool
的構造函數:
public?HttpConnectionPool(HttpConnectionPoolManager?poolManager,?HttpConnectionKind?kind,?string??host,?int?port,?string??sslHostName,?Uri??proxyUri)
{..._maxHttp11Connections?=?Settings._maxConnectionsPerServer;...
}
而HttpConnectionPool
的作用就是,提供到同一終結點的連接池。看來我們離真相越來越近了。
///?<summary>Provides?a?pool?of?connections?to?the?same?endpoint.</summary>
internal?sealed?class?HttpConnectionPool?:?IDisposable
HttpConnectionPoolManager
HttpConnectionPool
的構造函數只在HttpConnectionPoolManager
類中被調用:
public?ValueTask<HttpResponseMessage>?SendAsyncCore(HttpRequestMessage?request,?Uri??proxyUri,?bool?async,?bool?doRequestAuth,?bool?isProxyConnect,?CancellationToken?cancellationToken)
{HttpConnectionKey?key?=?GetConnectionKey(request,?proxyUri,?isProxyConnect);HttpConnectionPool??pool;while?(!_pools.TryGetValue(key,?out?pool)){pool?=?new?HttpConnectionPool(this,?key.Kind,?key.Host,?key.Port,?key.SslHostName,?key.ProxyUri);
可以看到,HttpConnectionPool
是從ConcurrentDictionary
_pools 中獲取的,而key的值是HttpConnectionKey
類型。
HttpConnectionKey
而 HttpConnectionKey 是這樣判斷是否相等的:
public?readonly?HttpConnectionKind?Kind;
public?readonly?string??Host;
public?readonly?int?Port;
public?readonly?string??SslHostName;?????//?null?if?not?SSL
public?readonly?Uri??ProxyUri;
public?readonly?string?Identity;public?bool?Equals(HttpConnectionKey?other)?=>Kind?==?other.Kind?&&Host?==?other.Host?&&Port?==?other.Port?&&ProxyUri?==?other.ProxyUri?&&SslHostName?==?other.SslHostName?&&Identity?==?other.Identity;
結論
由上面的代碼,我們可以得出如下結論:
如果連接類型、服務器地址、服務器端口、代理(如果有)全部相同,則認為是同一終結點
添加微信號【MyIO666】,邀你加入技術交流群