AWS Lambda RDS connection timeout

前端 未结 8 1627
栀梦
栀梦 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

    While using context will work, you just need to add context.callbackWaitsForEmptyEventLoop = false; to the handler and then use callback as normal like this:

    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');
      });
    };
    

    The answer is here in the docs (took me a few hours to find this): http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-using-old-runtime.html

    In the section "Comparing the Context and Callback Methods" it has an "Important" note that explains things.

    At the bottom of the note it reads:

    Therefore, if you want the same behavior as the context methods, you must set the context object property, callbackWaitsForEmptyEventLoop, to false.

    Basically, callback continues to the end of the event loop as opposed to context which ends the event loop. So setting callbackWaitsForEmptyEventLoop makes callback work like context.

提交回复
热议问题