Lambda Node.js Mysql RDS 超时

Lambda Node.js Mysql RDS Timeout

我用 Node.js 编写的 lambda 函数在连接到 RDS 时超时。

奇怪的是,这个超时只发生在第一次请求时。

所有后续请求都在没有超时的情况下使用数据库。

知道为什么吗?

仅供参考,未使用任何 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;
};

您可能会 运行 正在 运行 问题中释放您的池连接,同时(或之前)您的两个查询之一正在 运行。

创建池后,您无需显式调用 getConnection。更重要的是,如果您的代码中的查询可能会并行执行(就像您在此处所做的那样),则在管理连接时必须非常明智,并且只有在确定所有将使用它的查询都已完成后才释放它。

在此处阅读更多内容:(https://github.com/mysqljs/mysql#pooling-connections)

考虑尝试以下方法:

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