【问题标题】:"An operation on a socket could not be performed" with HttpClientFactory使用 HttpClientFactory “无法对套接字执行操作”
【发布时间】:2019-09-02 16:05:11
【问题描述】:

我在 Azure 上有一个长时间运行的触发式网络作业,它使用多个类型化的 http 客户端来访问远程服务。每次启动的请求数量高达数百万,但在大约 30k 之后,我得到了以下异常:

System.Net.Http.HttpRequestException:无法对套接字执行操作,因为系统缺少足够的缓冲区空间或队列已满。

我正在使用 Microsoft.Extensions.Http 2.2.0 通过 Http Client Factory 注入类型化的 http 客户端。

到目前为止,我已经尝试使用假数据和接收器在本地运行它;并监控与

的连接

netstat -b

...和

var ipProperties = IPGlobalProperties.GetIPGlobalProperties();

var tcpConnections = ipProperties.GetActiveTcpConnections();

...但我无法重现错误;并且连接数量始终保持不变。这让我认为连接限制以外的其他原因会导致此错误。

我会在 Azure 中尝试相同的方法;但这似乎不起作用,因为 Kudu 不允许 netstat 或类似命令。

客户端被添加到这样的服务中:

collection.AddHttpClient<ISenderClient, SenderClient>()
                .ConfigureHttpClient((provider, client) =>
            {
                 //... configuring base url and headers
            })
                .SetHandlerLifetime(TimeSpan.FromMinutes(1));

然后注入SenderClient:

public sealed class SenderClient : ISenderClient, IDisposable
    {
        private readonly HttpClient _httpClient;

        public SenderClient(HttpClient httpClient)
        {
            _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient));
        }

        public void Dispose()
        {
            _httpClient?.Dispose();
        }
    }

SenderClient 本身是从服务提供者那里获取的:

_client = _provider.GetService<ISenderClient>();

...后来在 Parallel.ForEach 循环中用于分发 http 请求:

Parallel.ForEach(batches, new ParallelOptions { MaxDegreeOfParallelism = 8 }, (batch, state, i) =>
            {
                using (var scope = _provider.CreateScope())
                {
                    var provider = scope.ServiceProvider;

                    //... dto mapping

                    var response = _client.SendAsync<Request, Response>(request).GetAwaiter().GetResult();
                 }
             }

SendAsync 在哪里

public async Task<TResponse> SendAsync<TRequest, TResponse>(TRequest request)
        {
            var json = JsonConvert.SerializeObject(request);
            using (var content = new StringContent(json, Encoding.UTF8, "application/json"))
            using (var response = await _client.PostAsync(_url, content))
            {
                var responseString = await response.Content.ReadAsStringAsync();
                return JsonConvert.DeserializeObject<TResponse>(responseString);
            }
        }

谁能解释一下什么可能导致这个异常,因为我现在很难尝试解决这个问题很长一段时间..?

编辑:我相信我的问题不是 this post 的重复,因为我使用的是 HttpClientFactory 而不是手动处理客户端。这应该负责管理、刷新和处理连接;并且被认为是处理 http 客户端的首选方式。

使用这种方法,我应该在某个时间段内只有一个类型的连接。

【问题讨论】:

标签: c# azure asp.net-core httpclient httpclientfactory


【解决方案1】:

我们将工作转移到具有更高定价层的应用服务,这在某种程度上解决了问题;虽然我对这个解决方案并不完全满意。

【讨论】:

    猜你喜欢
    • 2019-05-28
    • 2018-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-07
    • 1970-01-01
    • 2013-01-15
    相关资源
    最近更新 更多