如何停止出站HTTP连接超时

时间:2019-05-30 22:46:12

标签: linux azure docker asp.net-core kestrel

背景:

我目前正在Azure中托管具有以下规范的ASP.NET应用程序:

  • ASP .Net Core 2.2
  • 将Flurl用于HTTP请求
  • Kestrel Web服务器
  • Docker(Linux-mcr.microsoft.com/dotnet/core/aspnet:2.2运行时)
  • 有关P2V2层应用程序服务计划的Azure App Service

我在该服务上运行了一些后台作业,该作业对第三方服务进行了很多出站HTTP调用。

问题:

在较小的负载(每10秒大约1个呼叫)下,所有请求都将在不到一秒钟的时间内完成,而不会出现问题。我遇到的问题是,在负载沉重的情况下,当服务可以在10秒的时间内完成3/4个呼叫时,某些请求将随机超时并引发异常。当我使用RestSharp时,异常将显示为“操作已超时”。现在,我正在使用Flurl,该异常显示为“呼叫超时”。

这是关键-如果我从运行Windows 10 / Visual Studios 2017的笔记本电脑运行同一作业,则不会发生此问题。这使我相信我的托管环境正在达到某个极限或用尽了一些资源。不清楚是否与连接/套接字或线程相关。

我尝试过的事情:

  • 确保请求的所有代码路径都使用async/await来防止锁定
  • 确保Kestrel默认值允许无限制的连接(默认情况下确实如此)
  • 确保Docker的默认连接限制足够(默认情况下为2000,足够)
  • 为连接限制配置ServicePointManager设置

这是我当前用来尝试防止出现此问题的startup.cs中的代码:

public class Startup
{
    public Startup(IHostingEnvironment hostingEnvironment)
    {
        ...

        // ServicePointManager setup
        ServicePointManager.UseNagleAlgorithm = false;
        ServicePointManager.Expect100Continue = false;
        ServicePointManager.DefaultConnectionLimit = int.MaxValue;
        ServicePointManager.EnableDnsRoundRobin = true;
        ServicePointManager.ReusePort = true;

        // Set Service point timeouts
        var sp = ServicePointManager.FindServicePoint(new Uri("https://placeholder.thirdparty.com"));
        sp.ConnectionLeaseTimeout = 15 * 1000; // 15 seconds  

        FlurlHttp.ConfigureClient("https://placeholder.thirdparty.com", cli => cli.Settings.ConnectionLeaseTimeout = new TimeSpan(0, 0, 15));
    }
}

还有其他人遇到类似的问题吗?我愿意就如何最好地调试这种情况或纠正问题的可能方法提出任何建议。经过几天的研究,我完全不知所措。

谢谢。

1 个答案:

答案 0 :(得分:3)

我有类似的问题。看看Asp.net Core HttpClient has many TIME_WAIT or CLOSE_WAIT connections。通过netstat进行调试有助于为我确定问题。作为一种可能的解决方案。我建议您使用IHttpClientFactory。您可以从https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-2.2获取更多信息,如Flurl client lifetime in ASP.Net Core 2.1 and IHttpClientFactory

所述,它应该很容易使用