AWS Lambda RDS connection timeout

前端 未结 8 1631
栀梦
栀梦 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:27

    I have also faced similar timeout scenario. Issue was not doing connection.end() after connection.connect(). Connection.end() should be done before callback.

    Working Code:

      var mysql = require('mysql');
    
        var connection = mysql.createConnection({
            host     : 'host_name',
            user     : 'root',
            password : 'password'
        });
    
    
        module.exports.handler = (event, context, callback) => {
    
    // **Connection to database**      
    connection.connect(function(err) {
            if (err) {
              console.error('Database connection failed: ' + err.stack);
              return;
            }
            console.log('Connected to database.');
          });
    
        // **Hit DB Query**
          connection.query("Query", function(err, rows, fields) {
               console.log(rows);
            });
    
    
          //**Close Connection**
    
    connection.end(); ***// Missing this section will result in timeout***
    
        //**Send API Response**
          callback(null, {
                  statusCode: '200',
                  body: "Success",
                  headers: {
                      'Content-Type': 'application/json',
                  },
          });
    
        };
    

提交回复
热议问题