AWS Lambda RDS connection timeout

前端 未结 8 1649
栀梦
栀梦 2020-12-14 02:10

I\'m trying to write a Lambda function using Node.js which connects to my RDS database. The database is working and accessible from my Elastic Beanstalk environment. When I

8条回答
  •  别那么骄傲
    2020-12-14 02:46

    the connection.end() should be after callback:

    so working code:

        'use strict';
    var mysql = require('mysql');
    
    var connection = mysql.createConnection({
        host     : 'xxxxxx.amazonaws.com',
        user     : 'testuser',
        password : 'testPWD',
        port     : 3306,
        database: 'testDB',
        debug    : false        
    });
    
    module.exports.handler = (event, context, callback) => {
        // **Connection to database**      
        connection.connect(function(err) {
            if (err) {
                console.error('Database connection failed: ' + err.stack);
                context.fail();
                return;
            }
          else{ 
                console.log('Connected to database.');
            }
        });
    
        connection.query('show tables from testDB', function (error, results, fields) {
            if (error) {
                console.log("error: connection failed with db!");
                connection.destroy();
                throw error;
            } else {
                // connected!
                console.log("info: connection ok with db!");
                console.log(results);
                context.succeed("done");
                callback(error, results);
            }
        });
    
        //Send API Response
        callback(null, {
            statusCode: '200',
            body: 'succeed',
            headers: {
              'Content-Type': 'application/json',
            },
        });
    
        //Close Connection
        connection.end(); // Missing this section will result in timeout***
    
    };
    

提交回复
热议问题