【问题标题】:What is the right way to close the Database connection (Mysql) using Node.js and written inside AWS lambda使用 Node.js 并在 AWS lambda 中编写的关闭数据库连接(Mysql)的正确方法是什么
【发布时间】:2021-04-22 10:42:37
【问题描述】:

我正在使用用 node.js 编写的 finally 块来关闭我在代码中打开的数据库连接。下面附上代码sn-p。

我面临的问题 :- 当我在本地机器上执行以下代码时,我的 finally 块被执行,这得到安慰“dbconnection close 后的响应:”。

但是当我在 AWS lambda 中执行它时,我会从我的最后一个 then 块获得响应,并且当我的 finally 块执行时,它不会控制台函数日志中的“dbconnection close 后响应:”。

所以连接保持打开状态。

当我再次点击 lambda 函数时它会关闭。但留下了最新执行的 Open 连接。

请告诉我如何正确使用 finally 块或者我应该关闭最后一个连接然后块?

exports.executeSelectQueryPromise = (sql, args, parameters) => {

    sql = " SELECT * FROM ( " + sql + " ) as dataTable ";

    let DBConnection;

    return mysql.createConnection(process.env)
    .then(async (conn) => {
        DBConnection = conn;

        return DBConnection.query(sql, args);
    }).then(async (rows) => {
        let result = {
            "statusCode": 200,
            "headers": {
                "Access-Control-Allow-Origin": "*"
            },
            "body": [],
            "isBase64Encoded": false
        }

        return result;
    }).catch(async (error) => {
        console.log("Error: ", error);
        let err = {
            "statusCode": 400,
            "headers": {
                "Access-Control-Allow-Origin": "*"
            },
            "body": [],
            "isBase64Encoded": false
        }
        return err;
    })
    .finally(async () => {        
        
        console.log("DB connection type: ", typeof DBConnection);
        if (DBConnection && DBConnection.end) {
            DBConnection.end()
            .then(res => console.log("Response after dbconnection close: ", res))
            .catch(e => console.log("Error in dbconnection close: ", e));
        }
    });
}

【问题讨论】:

    标签: mysql node.js amazon-web-services aws-lambda database-connection


    【解决方案1】:

    更好的做法是在查询执行后立即关闭连接,无论执行成功与否。

    【讨论】:

      猜你喜欢
      • 2019-04-14
      • 1970-01-01
      • 1970-01-01
      • 2019-07-04
      • 2017-09-21
      • 1970-01-01
      • 1970-01-01
      • 2011-03-21
      • 1970-01-01
      相关资源
      最近更新 更多