问题描述
我将 Azure Functions 与队列触发器一起用于我们的部分工作负载.特定函数会查询数据库,这会产生扩展问题,因为大量并发 ping 数据库的函数实例会导致 Azrue DB 连接的最大允许数量不断受到影响.
I'm using Azure Functions with queue triggers for part of our workload. The specific function queries the database and this creates problems with scaling since the large concurrent number of function instances pinging the db results in maximum allowed number of Azrue DB connections being hit constantly.
这篇文章 https://docs.microsoft.com/en-us/azure/azure-functions/manage-connections 将 HttpClient 列为应设为静态的资源之一.是否也应该使用静态 SqlConnection 将数据库访问设为静态以解决此问题,或者通过保持恒定连接对象会导致其他一些问题?
This article https://docs.microsoft.com/en-us/azure/azure-functions/manage-connections lists HttpClient as one of those resources that should be made static.Should database access also be made static with static SqlConnection to resolve this issue, or would that cause some other problems by keeping the constant connection object?
推荐答案
绝对不是.每个函数调用都应该在 using 块中打开一个具有相同连接字符串的新 SqlConnection.目前还不清楚运行时将对应用程序的单个实例进行多少并发函数调用.但是如果大于1,那么单例SqlConnection就不好了.
Definitely not. Each function invocation should open a new SqlConnection, with the same connection string, in a using block. It's not really clear how many concurrent Function Invocations the runtime will make to a single instance of your application. But if it's more than 1, then a singleton SqlConnection is a bad thing.
我想知道究竟是哪个 限制 您在 SQL 数据库中遇到连接限制还是并发请求限制?在任何一种情况下,我都对你得到这么多并发函数调用感到有点惊讶(不是函数专家),所以可能还有其他事情发生.就像您正在泄漏 SqlConnections.
I wonder exactly which limit you're hitting in SQL Database, the connection limit or the concurrent request limit? In either case I'm a bit surprised (not a Functions expert) that you get that many concurrent function invocations, so there might be something else going on. Like you're leaking SqlConnections.
但阅读 Functions 文档后,我猜测函数运行时通过启动函数应用的多个实例来扩展.您的 .NET 应用程序可以在单个进程中扩展,但这显然不是 Functions 的工作方式.Functions 应用的每个实例都有自己的 SQL Server 连接池,默认情况下,每个连接池可以有 100 个连接.
But reading the Functions docs, my guess is that the functions runtime is scaling by launching multiple instances of your function app. Your .NET app could scale in a single process, but that's apparently not the way Functions works. Each instance of your Functions app has it's own ConnectionPool for SQL Server, and by default each ConnectionPool can have 100 connections.
也许如果您在连接字符串中严格限制最大池大小,就不会打开这么多连接.当您达到最大池大小时,对 SqlConnection.Open() 的新调用将阻塞长达 30 秒,等待池化 SqlConnection 变为可用.因此,这不仅限制了应用程序每个实例的连接使用,还限制了负载下的吞吐量.
Perhaps if you sharply limit the Max Pool Size in your connection string, won't have so many connections open. When you hit the Max Pool Size, new calls to SqlConnection.Open() will block for up to 30 seconds waiting for a pooled SqlConnection to become available. So this not only limits the connection use for each instance of your application, it throttles your throughput under load.
这篇关于Azure Functions 静态 SqlConnection - 正确的扩展方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!