CurrentConnections超过ServicePoint中的ConnectionLimit

时间:2017-09-14 18:46:52

标签: .net httpwebrequest httpclient httpconnection servicepoint

我有一个具有多个节点的集群/服务器,可以处理来自应用程序的请求。

用户正在运行的应用程序使用以下URL打开2个Web客户端:

为了支持粘性(我希望2个Web客户端中的每一个都能保持与节点的连接 - 持久性), ConnectionLeaseTimeout保留默认值,表示“不关闭连接” 由于DefaultPersistentConnectionLimit默认为2,因此我将DefaultConnectionLimit设置为1。

问题:

  1. servicePoint.CurrentConnections为2,尽管servicePoint.ConnectionLimit为1。

  2. 在服务器中,我看到远程主机端口正在发生变化,即我看到超过2个端口(每个客户端超过1个端口)。

  3. 我做错了什么?

    我的班级输出:

    CommunicationWebClient https://myprocess.myapp.com/api/json/v1

    CommunicationWebClient https://myprocess.myapp.com/api/protobuf/v1

    SendAsync _uri = https://myprocess.myapp.com/api/json/v1 servicePoint.Address = https://myprocess.myapp.com/api/json/v1 servicePoint.ConnectionLimit = 1 servicePoint.CurrentConnections = 2

    ...

    SendAsync _uri = https://myprocess.myapp.com/api/protobuf/v1 servicePoint.Address = https://myprocess.myapp.com/api/json/v1 servicePoint.ConnectionLimit = 1 servicePoint.CurrentConnections = 2

    ...

    public sealed class CommunicationWebClient : IDisposable
    {
        private HttpClient _httpClient;
        private Uri _uri;
    
        public CommunicationWebClient(Uri uri)
        {
            Logger.Debug($"{nameof(CommunicationWebClient)} {nameof(uri)}={uri}");
    
            _uri = uri;
    
            ServicePointManager.DefaultConnectionLimit = 1;
    
            _httpClient = new HttpClient(new WebRequestHandler())
            {
                Timeout = 10.Minutes(),
            };
        }
    
        public void Dispose()
        {
            _httpClient.Dispose();
        }
    
    
        public async Task SendAsync(
            ByteArrayContent content)
        {
            var servicePoint = ServicePointManager.FindServicePoint(_uri);
    
            Logger.Debug($"{nameof(SendAsync)} " +
                        $"{nameof(_uri)}={_uri} " +
                        $"{nameof(servicePoint.Address)}={servicePoint.Address} " +
                        $"{nameof(servicePoint.ConnectionLimit)}={servicePoint.ConnectionLimit} " +
                        $"{nameof(servicePoint.CurrentConnections)}={servicePoint.CurrentConnections}");
    
            using (var httpResponseMessage = await _httpClient.PostAsync(_uri, content))
            {
                ...
            }
        }
    }
    

1 个答案:

答案 0 :(得分:0)

如果仍有问题,请检查您的CommunicationWebClient是否过于频繁。它处理HttpClient但它的行为并不像通常人们期望的那样。

查看此文章:https://docs.microsoft.com/en-us/azure/architecture/antipatterns/improper-instantiation/

当你在Windows中处理HttpClient时,你会要求Windows关闭所有打开的套接字。但默认情况下,Windows有4分钟的超时时间来完全关闭套接字。因此,对于所有这4分钟,您的HttpClient和Web服务器之间将存在连接。