我正在尝试使用连接到我的 RDS 数据库的 Node.js 编写一个 Lambda 函数。该数据库正在运行并且可以从我的 Elastic Beanstalk 环境中访问。当我运行该函数时,它返回一个超时错误。
尝试将超时时间增加到 5 分钟,结果完全相同。
经过一番研究,我得出的结论是,这可能是一个安全问题,但在 Amazon 的文档或 this 中找不到解决方案。答案(这是我能找到的关于该主题的唯一答案)。
以下是安全细节:
- RDS 和 Lambda 都在同一个安全组中。
- RDS 具有所有流量入站和出站规则。
- Lambda 在其角色中具有 AmazonVPCFullAccess 策略。
我的代码是:
'use strict';
console.log("Loading getContacts function");
var AWS = require('aws-sdk');
var mysql = require('mysql');
exports.handler = (event, context, callback) => {
var connection = mysql.createConnection({
host : '...',
user : '...',
password : '...',
port : 3306,
database: 'ebdb',
debug : false
});
connection.connect(function(err) {
if (err) callback(null, 'error ' +err);
else callback(null, 'Success');
});
};
我得到的结果是:
"errorMessage": "2017-03-05T05:57:46.851Z 9ae64c49-0168-11e7-b49a-a1e77ae6f56c Task timed out after 10.00 seconds"
最佳答案
虽然可以使用上下文,但您只需将 context.callbackWaitsForEmptyEventLoop = false;
添加到处理程序,然后像这样正常使用回调:
exports.handler = (event, context) => {
context.callbackWaitsForEmptyEventLoop = false;
var connection = mysql.createConnection({
//connection info
});
connection.connect(function(err) {
if (err) callback(err);
else callback(null, 'Success');
});
};
答案在文档中(我花了几个小时才找到这个): http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-using-old-runtime.html
在“比较上下文和回调方法”部分中,它有一个“重要”说明来解释事情。
在注释的底部写着:
Therefore, if you want the same behavior as the context methods, you must set the context object property, callbackWaitsForEmptyEventLoop, to false.
基本上,回调会持续到事件循环的结束,而不是结束事件循环的上下文。所以设置 callbackWaitsForEmptyEventLoop 使得回调像上下文一样工作。
关于node.js - AWS Lambda RDS 连接超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42605093/