Azure Functions连接监视

问题描述

我的函数应用经常使用大量HTTP请求。所以我跟随以下错误

Only one usage of each socket address is normally permitted

功能应用程序将在几分钟后立即自动关闭。我对此进行了搜索,并了解到在每个restSharp请求中打开新连接都会导致该情况。更好的解决方案是仅以静态方式打开一个HttpClient。因此,我将功能更改为对所有请求使用静态HttpClient。

现在我想知道此更改是否正常进行。我检查了天蓝色矩阵中的连接,但它始终显示计数“ 30”。但在RestSharp的情况下也是如此。有人请帮助我了解分析连接图。 看到图片

enter image description here

enter image description here

感谢您的帮助。

解决方法

就错误消息而言,如果您只有30个连接,那么根据this的条款,这应该不是问题,除非并且除非您在Function App's host.json中将某些配置设置为30

在创建HttpClient静态实例之前,如果尚未使用它,则可以使用DI将HttpClient singleton 实例注入FunctionsStartup中-

using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;

[assembly: FunctionsStartup(typeof(MyNamespace.Startup))]

namespace MyNamespace
{
    public class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            builder.Services.AddSingleton<IHttpClient,HttpClient>();
        }
    }
}

然后,按如下方式使用您的客户端:

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
using System.Net.Http;
using System.Threading.Tasks;

namespace MyNamespace
{
    public class MyHttpTrigger
    {
        private readonly IHttpClient _client;

        public MyHttpTrigger(IHttpClient httpClient)
        {
            this._client = httpClient;
        }

        [FunctionName("MyHttpTrigger")]
        public async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function,"get","post",Route = null)] HttpRequest req,ILogger log)
        {
            var response = await _client.GetAsync("https://microsoft.com");    
            return new OkObjectResult("Response from function with injected dependencies.");
        }
    }
}

有关完整的实现和其他详细信息,您可以访问-https://docs.microsoft.com/en-us/azure/azure-functions/functions-dotnet-dependency-injection

编辑:

有关Azure App服务计划的指标的信息,您可以参考this文档。

这取决于您使HttpClient静态化的级别,在单例情况下始终建议使用DI。

根据Function App it scales out automatically,even during periods of high load的设计。我不确定第一个图,因为它不反映聚合。第二张图显示了沙箱(w3wp.exe及其子进程)中存在的绑定套接字数的平均值,并且正如您所提到的,我了解您的函数应用程序中有大量的出站Http请求,并且如果它们逐渐增加,如果出站请求数量最高(每个图为137个),则您的Azure Function App图看起来不错。请注意,the limit of Connections for each sand box of Free/Shared/Consumption is 600 and Basic+ Limit is Unlimited (VM limit still applies).如果您的出站Http请求超出了这些限制,那么您将不得不重新设计Function App,以使连接保持在这些限制之内。

如果您想在将来进行更深入的研究,可以参考this文档,以获取有关 Azure Function App Sandbox 的详细信息。该文件由PG定期维护。