HttpClientFactory没有重用相同的可用实例

时间:2020-01-08 02:11:11

标签: c# .net-core httpclient socketexception httpclientfactory

我有一个应用服务,该服务正在通过http调用来调用另一个。在测试我们的应用程序服务时,我们发现在我们的应用程序中实现的http客户端工厂正在导致工作负载上的套接字异常。

在进行调查后,我们发现对于每个请求,都有一个新的端口正在打开,而不会重用已经可用的已打开端口。

请找到我们的HttpClientFactory-类型客户端的当前实现:

我为测试而创建的api:

 [HttpGet("/api/RunFirstTest()")]
    public void RunFirstTest(int courseId, int learnerId)
    {
        for (int i = 0; i < 10; i++)
        {
            CourseSummarySM courseSummarySM = _courseSummaryService.GetCourseSummary(this.Token, courseId, learnerId);
        }
    }

DependencyInjection:

 public static IServiceCollection RegisterGateWayServer(
            this IServiceCollection services)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }
            // register http call services 
            services.AddHttpClient<IHttpCallService, HttpCallService>();
            services.AddTransient<IDefaultApiCalls, GateWayApiCalls>();
            return services;
        }

HttpCall类:

public class HttpCallService : IHttpCallService
{
    private readonly HttpClient _client;
    public HttpCallService(HttpClient client)
    {
        _client = client;
    }
    private HttpResponseMessage AuthorizedCall(HttpMethod verb, ApiModel model)
    {

        try
        {
            HttpRequestMessage request = new HttpRequestMessage(verb, model.url);

            if (model.data != null)
            {
                string jsonstring = JsonConvert.SerializeObject(model.data);//new JavaScriptSerializer().Serialize(model.data);
                if (verb.Method == HttpMethod.Post.Method || verb.Method == HttpMethod.Put.Method || verb.Method.Equals("patch", StringComparison.CurrentCultureIgnoreCase))
                {
                    request.Content = new StringContent(jsonstring, Encoding.UTF8, "application/json");
                }
            }
            _client.DefaultRequestHeaders.Clear();

            //add custom headers
            foreach (var kvp in model.headers)
                _client.DefaultRequestHeaders.Add(kvp.Key, kvp.Value.ToString());
            Task<HttpResponseMessage> X = _client.SendAsync(request);
            X.Wait();
            return X.Result;
        }
        catch (Exception e)
        {
        }
        finally
        {
            //if (_client != null)
            //    _client.Dispose();
        }
    }

请注意,我们正在使用存储库模式,因此课程摘要服务将使用存储库来进行其http调用

0 个答案:

没有答案
相关问题