问题
I was not able to connect to MySQL using AWS Lambda with Node.js.
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.
Below was the logs and the index.js
files and logs. Can anybody please guide me ?
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();
});
});
};
error :
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
回答1:
Try changing the lambda execution timeout from lambda console as shown in the below picture:
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.
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)=> {
After the work is finished, You need to callback to tell lambda that work is complete:
callback(undefined, result);
Example: https://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html#nodejs-prog-model-handler-example
回答2:
i followed my instructions given by @Dilip Kola , were my mistakes are not closing the pool , handler arguments !...
my complete code looks like now :
var mysql = require('mysql');
var pool = mysql.createPool({
host : 'url for mysql ',
user : 'username ',
password : 'paswrod ',
database : 'database-name'
});
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);
connection.release();
pool.end();
callback(null,rows[0].emp_name);
});
});
};
finally i got my output as :
来源:https://stackoverflow.com/questions/50789982/updated-aws-lambda-is-not-able-to-connect-to-mysql