简体   繁体   English

使用 Node.js 并在 AWS lambda 中编写的关闭数据库连接(Mysql)的正确方法是什么

[英]What is the right way to close the Database connection (Mysql) using Node.js and written inside AWS lambda

I am using the finally block written in node.js to close the database connection i have opened in the code.我正在使用用 node.js 编写的 finally 块来关闭我在代码中打开的数据库连接。 The code snippet is attached below.代码片段附在下面。

Problem i am facing:- When i execute the below code on local machine, my finally blocks gets executed and this gets consoled "Response after dbconnection close:".我面临的问题:-当我在本地机器上执行以下代码时,我的 finally 块被执行,这得到了安慰“dbconnection close 后的响应:”。

But when i am executing it in AWS lambda, i get response from my last then block and when my finally block executes it does not console the "Response after dbconnection close:" in function logs.但是,当我在 AWS lambda 中执行它时,我从最后一个 then 块中得到响应,当我的 finally 块执行时,它不会控制台 function 日志中的“dbconnection close 后响应:”。

So the connection remains open.所以连接保持打开状态。

It gets closed when i hit the lambda function again.当我再次击中 lambda function 时,它会关闭。 but leaves behind the Open connection from the latest execution.但留下了最新执行的 Open 连接。

Please let me know how to use finally block properly or shall i close the connection in last then block?请让我知道如何正确使用 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));
        }
    });
}

A much better practice is to close your connection soon after the query gets executed irrespective of being executed successful or unsuccessful.更好的做法是在查询执行后立即关闭连接,无论执行成功或不成功。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM