将AWS Lambda连接到rds的断开响应

问题描述

我正在尝试将lambda函数连接到rds,以便可以在Amazon Lex上查询它,但似乎无法获得与RDS的连接。 vpc和安全组部分已经解决,因为它们确实可以使用简单的功能。以下是我的代码示例。 $ {connection.status}返回断开连接。感谢您能给我任何帮助!

非常清楚,我实际上在顶部定义了一个调度功能。导出处理程序在下面进行。编辑了代码,使其非常清晰。

function dispatch(intentRequest,callback) {
    const sessionAttributes = intentRequest.sessionAttributes;
    const slots = intentRequest.currentIntent.slots;
    const MysqL = require('MysqL');

    var connection = MysqL.createConnection({
        host: 'xxx',user: 'admin',password: 'xxx',database: 'xxx',port: 3306
    });

    exports.handler = (event,context) => {
        connection.connect(function (err) {
            if (err) {
                context.fail();
            } else {
                context.succeed('Success');
            }
        });
    };

    callback(close(sessionAttributes,'Fulfilled',{
        'contentType': 'PlainText','content': `Thank you ${connection.state}`
    }));
}

// Route the incoming request based on intent.
// The JSON body of the request is provided in the event slot.
exports.handler = (event,context,callback) => {
    try {
        dispatch(event,(response) => {
            callback(null,response);
        });
    } catch (err) {
        callback(err);
    }
};

解决方法

由于RDS连接的初始化是异步的,因此需要在connection.connect的回调中移动逻辑

const mysql = require('mysql');

var connection = mysql.createConnection({
    host: 'xxx',user: 'admin',password: 'xxx',database: 'xxx',port: 3306
});

exports.handler = (event,context,callback) => {
    connection.connect(function (err) {
        if (err) {
            callback(err);
        } else {
            callback(null,close(sessionAttributes,'Fulfilled',{
                'contentType': 'PlainText','content': `Thank you ${connection.state}`
            }));
        }
    });
};

编辑: 请记住callback中参数的顺序。第一个参数应该是错误,第二个参数是响应。

,

我相信可能会发生一些异步处理,通过在connection.connect函数中使用回调,很可能在callback函数触发之前就达到了Lambdas connection.connect函数。

此外,将回调保留在exports.handler内。

尝试将您的功能更新为以下内容

const mysql = require("mysql");

 var connection = mysql.createConnection({
 host     : 'xxx',user     : 'admin',password : 'xxx',database : 'xxx',port : 3306
});

exports.handler = async (event,context) => {
 await connection.connect(function(err) {
   if (err) context.fail();
   else context.succeed('Success');
 });

callback(close(sessionAttributes,{'contentType': 'PlainText','content': `Thank you ${connection.state}`}));
};