简体   繁体   English

使用 Z3B2819DD4C24EDA2FAF2052EEF449555Z 从 AWS Lambda function 连接到 MySql 数据库

[英]Connecting to MySql database from AWS Lambda function using Node.js, no connect callback

I am trying to connect an external (not AWS) MySql server from an AWS Lambda function written in Node.js using nodejs14.x environment, but the connect() callback is not called. I am trying to connect an external (not AWS) MySql server from an AWS Lambda function written in Node.js using nodejs14.x environment, but the connect() callback is not called.

I am been struggling with this problem since days, there are a lot of references to similar issues but I really tried all possible permutations of solutions I found.几天以来我一直在努力解决这个问题,有很多类似问题的参考,但我真的尝试了我找到的所有可能的解决方案排列。

I am deploying with SAM and testing both on local machine and on real AWS.我正在使用 SAM 进行部署,并在本地机器和真正的 AWS 上进行测试。

Here is the sample code of the lambda helper这是 lambda 助手的示例代码

    const mysql = require('mysql');

    exports.helloFromLambdaHandler = async () => {

    const message = 'Hello from Lambda!';

    console.info(`${message}`);
    
    var sql = "SELECT 1+? AS sum";
    var values = [1];

    console.log("Doing createConnection");
    const connection = mysql.createConnection({
        /* my connection data */
      });
    
    console.log("Doing connect");
    connection.connect( (err) => {
        console.log("Inside connection callback");
        console.log('connected as id ' + connection.threadId);

        if(!err) {
          console.log("DB connected, thread id is "  + connection.threadId);
          console.log("Doing query");

          connection.query(sql, values, (err, result, values) => {
            console.log("Inside query callback");
            if(!err) {
              console.log("Query ok!");
              console.log(result);
              connection.end();
            } else {
              console.log("Error executing query: " + err.message);
            }       
          });
          
        } else {
          console.log("Error connecting db: "+ err.message);
        }
      });

    console.log ("Returning...");
    return message;
}

The log is日志是

Hello from Lambda!
Doing createConnection
Doing connect
Returning...

The expected behaviour is that after "Returning..." I should see the log "Inside connection callback" then "Inside query callback" and then "Query ok.".预期的行为是,在“返回...”之后,我应该看到日志“内部连接回调”,然后是“内部查询回调”,然后是“查询正常。”。

Instead the callback of connect() appears not invoked.相反, connect()的回调似乎没有被调用。

I know that I can call query() directly skipping connect() but also doing so I encounter same issue.我知道我可以直接调用query()跳过connect()但这样做我也会遇到同样的问题。

Any clue?有什么线索吗?

Thank you!谢谢!

SOLUTION解决方案

As suggested by the accepted answer, returning a promise is the solution to let Node complete all the queue.正如接受的答案所建议的那样,返回 promise 是让 Node 完成所有队列的解决方案。 Unfortunately it's not possible to complete the Lambda and leave it running in background in a safe manner, for what I understand.不幸的是,据我所知,不可能完成 Lambda 并让它以安全的方式在后台运行。

I am investigating alternative solutions such as:我正在研究替代解决方案,例如:

  • mysql2 library which supports promises natively原生支持 Promise 的mysql2
  • serverless-mysql npm package which handles shared db connections serverless -mysql npm package 处理共享数据库连接

Below the running demo code下面是运行的演示代码

const mysql = require('mysql');

exports.helloFromLambdaHandler = async (event, context) => {

    const message = 'Hello from Lambda!';

    console.info(`${message}`);
    
    var sql = "SELECT 1+? AS sum";
    var values = [1];

    console.log("Doing createConnection");
    const connection = mysql.createConnection({
        /* my connection data */
      });
    
    console.log("Doing query");

    const promise = new Promise( (resolve, reject) => {
        connection.query(sql, values, (err, result, values) => {
        console.log("Inside query callback");
        if(!err) {
            console.log("Query ok!");
            console.log(result);
            connection.end();
            resolve(message);
        } else {
            console.log("Error executing query: " + err.message);
            reject(err);
        }       
        });
    });

    console.log ("Returning...");
    return promise;
}

You are using async handler , thus your function probably completes before your connect() has a chance to execute.您正在使用async handler ,因此您的 function 可能在您的connect()有机会执行之前完成。

To try to overcome the issue, you can use Promise as shown in AWS docs .要尝试解决此问题,您可以使用Promise ,如AWS 文档中所示。

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

相关问题 使用node.js和AWS Lambda将Alexa技能连接到mysql数据库 - Connecting Alexa skill to mysql database using node.js and aws lambda 使用 Node.js 并在 AWS lambda 中编写的关闭数据库连接(Mysql)的正确方法是什么 - What is the right way to close the Database connection (Mysql) using Node.js and written inside AWS lambda 如何连接到 node.js 中的 AWS MySQL 数据库 - How do I connect to an AWS MySQL database in node.js 无法从 Heroku 或 Replit 网站连接到存储在 aws 上的数据库。 (mysql2, node.js) - Cannot connect to database stored on aws from Heroku or Replit websites. (mysql2, node.js) 从 Stackblitz Node.js 项目连接到远程 MySQL 数据库 - Connecting to a remote MySQL database from Stackblitz Node.js project 如何使用连接到数据库的 Node.js 和 mysql2 调试 Azure 函数 - How to debug an Azure Function using Node.js and mysql2 connecting to database 使用来自node.js的jdbc连接到mysql - connecting to mysql using jdbc from node.js 无法使用 node.js 连接到 mysql 数据库 - cannot connect to mysql database using node.js 无法使用openshift node.js连接到外部mysql数据库 - Cannot connect to external mysql database using openshift node.js 如何使用 Node.js 连接到远程 mysql 数据库 - How to connect to remote mysql database using Node.js
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM