mysql - 在 .NET AWS Lambda 中使用 MySql.Data 和 D.I

标签 mysql .net aws-lambda dependency-injection

我正在重构一个包含 MySql.Data 的 .NET AWS Lambda 项目,以连接到 AWS Aurora。我实现了 DI 流程,并将 MySqlConnection 作为 Transient 注册到 DI 容器中,并将其注入(inject)到 DataAccess 服务中。

MySqlConnection 和 DataAccess 的注册过程如下:

启动:

services.AddTransient<MySqlConnection>(provider => 
{
    //Get the necessary parameters and build a connection string.

    return new MySqlConnection(connectionString);
});

services.AddSingleton<IDataAccess, DataAccess>();

数据访问:

private readonly MySqlConnection _connection;

// inject the MySqlConnection.

async function() 
{
  await _connection.OpenAsync();
  await _connection.DoStuff();
  await _connection.CloseAsync();
}

我的老板担心所有数据库交互都将通过注入(inject) DataAccess 类的单个连接进行,她不希望数据库崩溃,因为我没有正确清理连接。

我有几个问题:

  1. 我看到旧的代码库在创建新的 MySqlConnection 时有 using 语句,但我在 MySql 文档中没有看到该语句。创建新的 MySqlConnection 时是否需要“using”语句?
  2. 我应该将 MySqlConnection 注册为 Transient 并使用 DI 还是只是在使用它的类中创建一个新的 MySqlConnection 实例?
  3. DB 连接的 DI 是否会留下大量打开的连接?或者,在另一个极端,单个连接会减慢 lambda 的速度,因为它过去需要建立大量连接?

谢谢!

最佳答案

IMO,您可以使用 using 语句,而不是使用 DI。 SQL 连接将从 .NET 在应用程序级别维护的池中选取,并在连接关闭后返回。引用这个answer了解更多详情。

但是,连接池对于 AWS Lambda 没有太大帮助,因为整个 Lambda 计算在空闲超时后会被销毁。所以推荐使用RDS proxy以避免连接相关问题。

Using RDS Proxy, you can handle unpredictable surges in database traffic. Otherwise, these surges might cause issues due to oversubscribing connections or creating new connections at a fast rate. RDS Proxy establishes a database connection pool and reuses connections in this pool. This approach avoids the memory and CPU overhead of opening a new database connection each time. To protect the database against oversubscription, you can control the number of database connections that are created.

此外,您还可以结账RDS Proxy for SQL Server with AWS Lambda and .NET 6

关于mysql - 在 .NET AWS Lambda 中使用 MySql.Data 和 D.I,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76337662/

相关文章:

php - 从 BLOB 中删除信息

php - 向后插入关注关系

Node.js 未按预期输出

json - 使用Lambda部署时,fs.readFileSync无法找到文件

amazon-web-services - API 网关是否引入了显着延迟?

php - 捕获组中的正则表达式括号

mysql - 如何解决使用node.js向mysql插入数据时出现的错误

.net - 如何在 Web Api 中手动执行 Breeze 过滤器?

.net - 由于编码问题,WebClient.DownloadString 导致字符损坏,但浏览器正常

c# - 如何处理 WPF 验证和 MVVM?