已更新:AWS Lambda无法连接到MySQL
我无法使用带有Node.js的AWS Lambda连接到MySQL.
I was not able to connect to MySQL using AWS Lambda with Node.js.
我曾尝试为AWS MySQL和Lambda配置安全组.当我使用console.log
时,它会以the data from db : rk
的形式显示来自数据库的正确响应,但是当我尝试进行测试时,它并未显示正确的响应.
I had tried configured the security groups for AWS MySQL and Lambda. When I used console.log
it shows correct response from the data base as the data from db : rk
, but when I tried to test it was not showing the correct response.
下面是日志以及index.js
文件和日志.有人可以指导我吗?
Below was the logs and the index.js
files and logs. Can anybody please guide me ?
index.js(我已经更新了我的代码,如下所示):
index.js (i had updated my code as below ):
var mysql = require('mysql');
var pool = mysql.createPool({
host : 'mydbinstancelamda.connqa9taxeg.us-east-1.rds.amazonaws.com',
user : 'admin',
password : 'password',
database : 'dbname'
});
exports.handler = (event, context, callback)=> {
pool.getConnection(function(err, connection) {
if (err) throw err;
var queryString = "SELECT emp_name from employee where emp_name='rk'";
connection.query(queryString, function(err, rows, fields) {
if (err) throw err;
console.log("the data from db : " + rows[0].emp_name);
callback(null);
connection.release();
});
});
};
错误:
Response:
{
"errorMessage": "2018-06-11T02:34:19.817Z ef864d3d-6d1f-11e8-b6e3-97ac89a0f544 Task timed out after 3.00 seconds"
}
Request ID:
"ef864d3d-6d1f-11e8-b6e3-97ac89a0f544"
Function Logs:
START RequestId: ef864d3d-6d1f-11e8-b6e3-97ac89a0f544 Version: $LATEST
dadf1a33-6d22-11e8-869d-7d7e31ccaf6e the data from db : rk
END
尝试从lambda控制台更改lambda执行超时,如下图所示:
Try changing the lambda execution timeout from lambda console as shown in the below picture:
确保RDS MySQL DB的安全组允许来自Lambda的安全组的连接,如果存在相同的连接,那么您就很好了.
Make sure that security group of RDS MySQL DB is allowing connections from Lambda's security group, if there are the same then you are good to go.
更新: MySQL返回响应后,您需要调用回调.
UPDATE: You need to call callback after the MySQL returns the response.
// change following line:
exports.handler = (event, context, req,res,callback)=> {
// To this line:
exports.handler = (event, context, callback)=> {
工作完成后,您需要回调以告知lambda工作已完成:
After the work is finished, You need to callback to tell lambda that work is complete:
callback(undefined, result);