Azure 函数支持连接池或任何其他重用相同 db 实例的方式 [英] Azure function support for connection pooling or any other way to reuse same instance of db
问题描述
由于 AWS Lambda 支持连接池,如 Link.
As AWS Lambda support Connection pooling as shown in the Link.
根据我的要求,我将在 kafka 中使用触发功能.但是对数据库的请求会发生得如此频繁,以至于它可以使用很高比例的 cpu.所以为了避免我想使用连接池或任何其他方式来使用相同的数据库上下文实例.
As per my requirement i will use trigger function with kafka. But the request to database is gonna happen so frequent that it can use high percentage of cpu. So to avoid that i want to use connection pooling or any other way to use same instance of database context.
推荐答案
在 Azure Functions 中,您可以(并且应该)创建一个在启动时初始化的共享连接对象,而不是在每次调用函数时都创建一个新对象.
In Azure Functions you can (and should) create a shared connection object initialized at startup time instead of creating a new one with every function invocation.
如果你使用 C#,ADO.NET 实际上已经为你管理了一个 SQL 连接池,所以如果你关闭一个连接,它就是 只是放回池中:
If you use C#, ADO.NET actually manages a SQL connection pool already for you so if you close a connection, it is just put back to the pool:
using System.Data.SqlClient;
private static SqlConnection client = InitializeSQLConnection();
private static SqlConnection InitializeSQLConnection()
{
string connetionString = "...";
return new SqlConnection(connetionString);
}
[FunctionName("MyFunction")]
public static void Run(...)
{
connection.Open(); // Get a connection object from the pool
// Execute queries on connection
connection.Close(); // Put the connection object back to the pool
}
如果您使用 Python,请在 main()
函数之外初始化数据库连接.
If you use Python, initialize the database connection outside the main()
function.
import azure.functions as func
connection = SQLConnection(...) # class you implement that connects to the SQL server
def main(events: List[func.EventHubEvent]):
# do something with the connection
还有一个 JavaScript 示例这里.
There is also a JavaScript example here.
这篇关于Azure 函数支持连接池或任何其他重用相同 db 实例的方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!