简体   繁体   English

Node.js MySQL如何处理超时和握手不活动超时

[英]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. 我是Nodejs的新手,我在NodeJS上编写了一个lambda函数,该函数应该删除一些行并在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. 我遇到了各种带有错误消息的实例,例如PROTOCOL_SEQUENCE_TIMEOUT,PROTOCOL_CONNECTION_LOST,以及一个RDS数据库dns无法解析并连接到数据库的实例。

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. 您可以缓存连接,因此第一次调用lambda将创建连接,而第二次调用(如果lambda不是冷启动的)可以重用该连接,并且速度更快。

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. 您还可以在catch块中进行连接重试。

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

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