我应该关闭 AWS Lambda 函数内的 RDS 代理连接吗?

Should I close an RDS Proxy connection inside an AWS Lambda function?

我将 Lambda 与 RDS 代理结合使用,以便能够重复使用与 MySQL 数据库的数据库连接。

我是应该在执行完查询后关闭连接,还是让它保持打开状态以供 RDS 代理处理?

如果我应该关闭连接,那么首先使用 RDS 代理有什么意义?

这是我的 lambda 函数的示例:

const mysql = require("mysql2/promise")

exports.handler = async (event) => {
  let connection

  try {
    connection = await mysql.createConnection({
      host: process.env.RDS_HOST, // RDS Proxy endpoint here
      user: process.env.RDS_USER,
      database: process.env.RDS_DATABASE,
      password: process.env.RDS_PASSWORD,
      ssl: "Amazon RDS"
    })
    console.log(`Connected to db. ConnectionId: ${connection.threadId}`)

    // Do some queries
  } catch (err) {
    return handleError(err)
  } finally {
    if (connection) await connection.end() // Should I close the connection here?
  }

  return response(200, "Success")
}

编辑: 注意在处理程序外部初始化连接(global scope)将使 lambda 函数在同一执行中的调用之间保留连接变量的值短时间内多次调用lambda函数时会出现如下错误Can't add new command when connection is in closed state 因为连接已经关闭了第一次调用,所以我最好建议在处理程序内部而不是外部定义连接。

TDLR:始终关闭数据库连接

RDS 代理位于您的应用程序和数据库之间,除了使用代理端点外,不应导致任何应用程序更改。


Should I close the connection after executing my queries or leave it open for the RDS Proxy to handle?

无论是否使用数据库代理,都不应让数据库连接处于打开状态。

连接是一种有限且相对昂贵的资源。

经验法则是尽可能晚地打开连接并尽可能尽快关闭数据库连接。未明确关闭的连接可能不会添加或返回到池中。关闭数据库连接是一个很好的数据库客户端。

将数据库资源与许多打开的连接捆绑在一起,您会发现自己的数据库实例需要更多 vCPU,这会导致更高的 RDS 代理价格标签。


And if I should close the connection, then what's the point of using an RDS Proxy in the first place?

重点是您的 Amazon RDS 代理实例 maintains a pool of established connections to your RDS database instances 为您 - 它位于 您的应用程序和您的 RDS 之间 数据库。

代理不负责关闭您建立的本地连接,也不应该关闭。

它负责管理连接 multiplexing/pooling 并为需要它的应用程序自动共享。

AWS docs:

中明确提到了需要它的 应用程序示例

Many applications, including those built on modern serverless architectures, can have a large number of open connections to the database server, and may open and close database connections at a high rate, exhausting database memory and compute resources.


为避免任何疑问,请随时查看 AWS 提供的关闭连接的示例 here (linked to from docs), or another one in the AWS Compute Blog here