简体   繁体   English

Lambda Node.js Mysql RDS超时

[英]Lambda Node.js Mysql RDS Timeout

My lambda function written in Node.js times out when connecting to RDS. 连接到RDS时,用Node.js编写的lambda函数超时。

Weird thing is, this timeout happens only for the first request. 奇怪的是,此超时仅发生在第一个请求上。

All subsequent requests work with the DB without the timeout. 所有后续请求均可与数据库一起使用,而不会超时。

Any idea why? 知道为什么吗?

Just FYI not using any VPCs. 仅供参考,不使用任何VPC。

var mysql = require('mysql');

var pool = mysql.createPool({
  host     : 'ahost',
  user     : 'auser',
  password : 'apassword',
  database : 'adb',
  port : 3306
});


exports.handler = async (event, context) => {
    let request = JSON.parse(event.body);
    let question = request.question;
    let answered = question.answered;
    let sId = request.sid;
    let questionnaireId = request.questionnaireId;
    let hutk = request.hutk;
    let questionId = question.question.id;

    pool.getConnection((error, connection) => {
        if (error) throw error;
        let values = [];
        if(Array.isArray(answered)){
            let i = 0;
            while(i < answered.length){
                let td = [
                    questionnaireId,
                    sId,
                    questionId,
                    answered[i],
                    hutk
                ];
                values.push(td);
                i++;
            }
        } else {
            let td = [
                questionnaireId,
                sId,
                questionId,
                answered,
                hutk
            ];
            values.push(td);
        }

        let delsql = "DELETE FROM answers WHERE sId= ? AND `key` = ?";
        connection.query(delsql, [sId, questionId], function(err, result){
            if(err) throw err;
        });

        let sql = "INSERT INTO answers (qId, sId, `key`, value, hutk) VALUES ?";
        connection.query(sql, [values], function(err, result){
            if(err) throw err;
            console.log("Successfull Insert")
            connection.release();
        });

    });

    // TODO implement
    const response = {
        statusCode: 200,
        headers: {
                    'Access-Control-Allow-Origin': '*',
                    'Access-Control-Allow-Credentials': true
                },
        body: JSON.stringify({message : 'success'}),
    };

    return response;
};

You might be running into and issue where you're releasing your pool connection while (or prior to) one of your two queries is being run. 您可能会遇到问题,并且在运行两个查询之一(或之前)时释放池连接。

You don't need to explicitly call getConnection once you've created the pool. 创建池后,无需显式调用getConnection More importantly if you have code where queries might execute in parallel (as you do here) you have to be very judicious in managing the connection and only releasing it once you're certain all the queries that will use it have completed. 更重要的是,如果您具有可以并行执行查询的代码(如此处所述),则必须非常谨慎地管理连接,并且只有在确定将使用该连接的所有查询完成后才释放它。

Read more here: ( https://github.com/mysqljs/mysql#pooling-connections ) 在此处阅读更多信息:( https://github.com/mysqljs/mysql#pooling-connections

Consider trying the following: 考虑尝试以下方法:

var mysql = require('mysql');

var pool = mysql.createPool({
  host: 'ahost',
  user: 'auser',
  password: 'apassword',
  database: 'adb',
  port: 3306
});

pool.on('connection', function (connection) {
  console.log('Pool id %d connected', connection.threadId);
});

pool.on('enqueue', function () {
  console.log('Waiting for available connection slot');
});

exports.handler = async (event, context) => {
  let request = JSON.parse(event.body);
  let question = request.question;
  let answered = question.answered;
  let sId = request.sid;
  let questionnaireId = request.questionnaireId;
  let hutk = request.hutk;
  let questionId = question.question.id;

  let values = [];
  if (Array.isArray(answered)) {
    let i = 0;
    while (i < answered.length) {
      let td = [
        questionnaireId,
        sId,
        questionId,
        answered[i],
        hutk
      ];
      values.push(td);
      i++;
    }
  }
  else {
    let td = [
      questionnaireId,
      sId,
      questionId,
      answered,
      hutk
    ];
    values.push(td);
  }

  let delete_query = "DELETE FROM answers WHERE sId= ? AND `key` = ?";
  pool.query(delete_query, [sId, questionId], function(err, result) {
    if (err) throw err;
  });

  let insert_query = "INSERT INTO answers (qId, sId, `key`, value, hutk) VALUES ?";
  pool.query(insert_query, [values], function(err, result) {
    if (err) throw err;
    console.log("Successfull Insert")
  });

  // TODO implement
  const response = {
    statusCode: 200,
    headers: {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Credentials': true
    },
    body: JSON.stringify({
      message: 'success'
    }),
  };

  return response;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM