简体   繁体   中英

Nodejs mysql how to handle timeout and Handshake inactivity timeout

I am a newbie in Nodejs and I have a lambda function written on NodeJS that's supposed to delete some rows and insert some data on a mysql db. I have come across various instances with error messages such as PROTOCOL_SEQUENCE_TIMEOUT, PROTOCOL_CONNECTION_LOST and an instance where the RDS db dns couldn't be resolved and connect to the db.

I was wondering how I might handle these events so I'd be able to re-connect and proceed.

var mysql = require('mysql');

var pool = mysql.createPool({
  host     : 'somehost',
  user     : 'someuser',
  password : 'somepassword',
  database : 'somedb',
  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) => {
    context.callbackWaitsForEmptyEventLoop = false;
    let request = JSON.parse(event.body);

    /** SOME OTHER LOGIC HERE **/

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

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

And also am I using the best approach to connecting to the db as in a pool or should I be using just a connection etc?

You can cache the connection, so the first call to your lambda would create the connection and the 2nd call (if the lambda is not cold started) can reuse the connection and is much faster.

Here is how we do it:

  const mysql = require('mysql');
const util = require('util');

let mySQLconnection = undefined;

exports.handler = async function handler(event, context) {
    try {
        getMySQLConnection();
        const queryResult = await mySQLconnection.query('Select * from yourtable where id = ? and attribute = ?', [id, attribute]);
    } catch (error) {
        console.log('ERROR: ' + error);
    }
};

function getMySQLConnection() {
    if (mySQLconnection !== undefined) {
        return;
    }
    mySQLconnection = mysql.createConnection(yourConnectionJson);
    mySQLconnection.query = util.promisify(mySQLconnection.query);
}

You could also do a connection retry in the catch block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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