首页 > 解决方案 > Lambda Node.js Mysql RDS 超时

问题描述

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

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

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

知道为什么吗?

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

标签: mysqlnode.jsaws-lambdards

解决方案


在运行两个查询之一时(或之前),您可能会遇到并发布池连接的问题。

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

推荐阅读