编程语言
首页 > 编程语言> > c# – 通过HTTP调用Azure功能150次导致异常

c# – 通过HTTP调用Azure功能150次导致异常

作者:互联网

我在Azure上运行asp.net mvc Web App.在一个方法中,我对Azure Function Web API进行了几次HTTP调用.在此Azure函数中,我使用DbContext将新记录插入数据库.

// Method in web application making http requests to azure function web api
public async Task CreateRecords() {
    int amountOfCalls = 150;
    var allTasks = new List<Task<HttpResponseMessage>>();

    for (int i = 0; i < amountOfCalls; i++) {
        var task = HttpClientInstance.Instance.PostAsync(<uri>, new StringContent(i.ToString()));
        allTasks.Add(task);
    }

    await Task.WhenAll(allTasks); // Gives an exception
}

当amountOfCalls设置为25,50或100时,一切都很好.但是,当我将amountOfCalls设置为150时,最初它会将一些记录插入到数据库中,但最终会导致错误:

Unable to connect to the remote server.

所以首先我认为它必须是Azure sql数据库的最大并发登录.所以我将那个升级到定价层S9(1600 DTU,最多3200个并发登录,标注为here).

但这并没有解决问题.然后我开始远程调试Azure功能.并且它不会在Azure功能本身中提供异常.
因此,下一步是研究Application Insights.我看到DbContext的构造函数给出了一个异常(不幸的是没有堆栈跟踪):

type: System.InvalidOperationException

method: WebApp.DataAccess.PocDbContext..ctor

requestName: InsertRecordFunction

requestDuration: 55,643.2201

Azure Function看起来像这样:

[DependencyInjectionConfig(typeof(DependencyConfig))] // Autofac
public static class InsertRecordFunction
{
    [FunctionName("InsertRecordFunction")]
    public static async Task<HttpResponseMessage> Run(
        [HttpTrigger(AuthorizationLevel.Function, "post", Route = "InsertRecordFunction")]HttpRequestMessage req,
        TraceWriter log,
        [Inject]IRecordDataService recordDataService)
    {
        log.Info("InsertRecordFunction was triggered by Http.");
        try {
            await recordDataService.AddRandomRecordAsync();
        }
        catch (Exception ex) {
            return req.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
        }

        return req.CreateResponse(HttpStatusCode.OK);
    }

而PocDbContext的代码如下:

public PocDbContext() : base("DefaultConnection") {
    Database.SetInitializer<PocDbContext>(null);
}

我仍然觉得它与连接池到Azure sql数据库有关.在此问题出现之前,我遇到另一个告诉我将执行策略设置为SqlAzureExecutionStrategy(我做了this way).

使用(静态)HttpClient从Azure Web App进行的Web api调用是否存在某种最大值?我还能做些什么来找出确切的例外情况?谢谢.

更新

在Application Insights中,我找到了有关异常的其他信息:

Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.

升级Azure sql数据库的定价层后,不是我所期望的.

解决方法:

来自ADO.NET的文档,它是实体框架(SQL Server Connection Pooling (ADO.NET))的基础:

By default, connection pooling is enabled in ADO.NET. Unless you explicitly disable it, the pooler optimizes the connections as they are opened and closed in your application.

Adding Connections部分稍微向下:

Connections are added to the pool as needed, up to the maximum pool size specified (100 is the default).

因此明确地将连接字符串的最大池大小设置为> = 150应该可以解决问题.

标签:c,asp-net-mvc,azure-web-sites,dotnet-httpclient,azure-functions
来源: https://codeday.me/bug/20190627/1305436.html