我正在尝试学习如何使用AWS中的lambda函数连接MySQL。我已经按照网上的一些说明进行操作,基本上得到了以下代码:



    var mysql = require('mysql');
    var pool  = mysql.createPool({
        connectionLimit : 1000,
        connectTimeout  : 60 * 60 * 1000,
        acquireTimeout  : 60 * 60 * 1000,
        timeout         : 60 * 60 * 1000,
        host: "foo-bar-123.us-east-2.rds.amazonaws.com",
        user: "root",
        password: "pass123",
        database: "sample_db",
    });

    exports.handler =  (event, context, callback) => {
      // prevent timeout from waiting event loop
      context.callbackWaitsForEmptyEventLoop = false;

      pool.getConnection(function(err, connection) {
        if (err) throw err;

        // Use the connection
        connection.query('SELECT id FROM customer limit 10;', function (error, results, fields) {
          // And done with the connection.
          connection.release();
          // Handle error after the release.
          if (error) callback(error);
          else callback(null,results);
        });
      });
    };



这在我的本地计算机上有效,但是当我压缩此代码并将其作为lambda函数上传时,这将返回

Response: { "errorMessage": "2018-11-13T02:16:10.339Z 0562b432-e6ea-11e8-81ef-bd64aa1af0a4 Task timed out after 30.03 seconds" }

无论我将其设置为多少秒,它都会超时。

因为我是所有这些的新手,所以我几乎将所有设置都设置为默认,但是我已经将Lambda函数的角色添加了AmazonRDSFullAccess。

有人知道我的设置中可能有什么错误或遗漏吗?

谢谢。

最佳答案

经过一些尝试和错误之后,我能够使其正常运行,而我所缺少的是我不允许RDS Security组的入站中使用All TCP。在那之后,我将其设置为No VPC作为我的lambda函数,它能够正确查询。

此链接:https://dzone.com/articles/querying-rds-mysql-db-with-nodejs-lambda-function和其中发布的堆栈溢出链接(即:AWS Lambda RDS connection timeout)对我弄清楚我的代码/设置有什么问题大有帮助。

这是我最终使用的最终代码。



    const mysql = require('mysql');
    const pool  = mysql.createPool({
        host: "foo-bar-123.us-east-2.rds.amazonaws.com",
        user: "root",
        password: "pass123",
        database: "sample_db"
    });

    exports.handler = (event, context, callback) => {
      //prevent timeout from waiting event loop
      context.callbackWaitsForEmptyEventLoop = false;

      pool.getConnection((err, connection) => {
        if(err) throw err;

        // Use the connection
        connection.query('SELECT id FROM customer limit 10;', (error, results, fields) => {

          // And done with the connection.
          connection.release();

          // Handle error after the release.
          if (error) callback(error);
          else callback(null,results);
        });
      });
    };



谢谢!

关于mysql - Lambda NodeJS MySQL任务超时,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53273063/

10-10 22:01
查看更多