【问题标题】:HttpClient performance issues when deployed部署时的 HttpClient 性能问题
【发布时间】:2019-11-26 14:48:18
【问题描述】:

我有下面的代码。在本地运行它,我会在不到 1 秒的时间内从 API 获得响应。

当我将它部署到服务器时,需要 3 到 10 分钟才能得到响应!

我已部署到 3 个不同的服务器,结果相同。知道可能出了什么问题吗?

下面是我的代码:

string response = string.Empty;
try
{
    var content = new StringContent(JsonConvert.SerializeObject(request), System.Text.Encoding.UTF8, "application/json");

    using (var client = new HttpClient())
    {
        var responseMessage = client.PostAsync("https://myapi/createshorturl", content).Result;
        response = responseMessage.Content.ReadAsStringAsync().Result;
        return JsonConvert.DeserializeObject<CreateShortUrlResponse>(response);
    }
}
catch (Exception x)
{
    return null;
}

【问题讨论】:

  • 服务器在拨号,服务器在慢速代理后面,等等。对此我们无话可说,代码无关紧要。
  • phuzi,对我来说,该评论将是一个“答案”。否则很容易被忽视。
  • catch (Exception x) { return null;} ???你确定你没有收到很多个被简单掩盖的异常吗?
  • @johnny5 我的评论意味着代表可能原因列表的开始。实在是太多了。

标签: c# .net dotnet-httpclient


【解决方案1】:

您可能使用错误的 HttpClient。继续使用前先看看以下文章:

TL;DR:

  • HttpClient 持有底层套接字的时间比你想象的要长。
  • 重用HttpClient,不要为每个请求创建一个新的。
  • 使用 IHttpClientFactory
  • 不要.Result

【讨论】:

    【解决方案2】:

    HttpClient 实例应该被重用,这应该是您在这里进行更改的第一站。其次,如果可以避免,请不要永远使用Task.Result。这是一个同步调用,可能会在负载下落后。

    class Something
    {
        HttpClient client = new HttpClient();
    
        public async Task<CreateShortUrlResponse> GetResponseAsync()
        {
            string response = string.Empty;
    
            try
            {
                var content = new StringContent(JsonConvert.SerializeObject(request), System.Text.Encoding.UTF8, "application/json");
    
                {
                    var responseMessage = await client.PostAsync("https://myapi/createshorturl", content);
                    response = await responseMessage.Content.ReadAsStringAsync();
                    return JsonConvert.DeserializeObject<CreateShortUrlResponse>(response);
                }
            }
            catch (Exception x)
            {
                //you should log something here, rather than silently returning null. Or let it propagate up to where it can be handled.
                return null;
            }
        }
    }
    

    【讨论】:

    • @mason 谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多