Reproduce MySQL error: The server closed the connection (node.js)

后端 未结 5 1788
你的背包
你的背包 2020-12-25 14:38

I\'m trying to reproduce a MySQL error I\'m seeing in my node.js app on EC2 with the node mysql library:

Connection lost: The server closed the connec

5条回答
  •  眼角桃花
    2020-12-25 15:32

    Here's what I ended up using, and it worked pretty well. On the occasional connection lost/restart it recovered nicely. I have a database.js file which establishes connections and checks them periodically.

    To make a request:

    var conn = require('./database');
    var sql = 'SELECT foo FROM bar;';
    conn.query(sql, [userId, plugId], function (err, rows) {
       // logic
    }
    

    Here's my databbase.js

    var mysql = require('mysql');
    var Common = require('./common');
    var conf = Common.conf;
    var logger = Common.logger;
    
    var connectionState = false;
    var connection = mysql.createConnection({
      host: conf.db.hostname,
      user: conf.db.user,
      password: conf.db.pass,
      database: conf.db.schema,
      insecureAuth: true
    });
    connection.on('close', function (err) {
      logger.error('mysqldb conn close');
      connectionState = false;
    });
    connection.on('error', function (err) {
      logger.error('mysqldb error: ' + err);
      connectionState = false;
    });
    
    function attemptConnection(connection) {
      if(!connectionState){
        connection = mysql.createConnection(connection.config);
        connection.connect(function (err) {
          // connected! (unless `err` is set)
          if (err) {
            logger.error('mysql db unable to connect: ' + err);
            connectionState = false;
          } else {
            logger.info('mysql connect!');
    
            connectionState = true;
          }
        });
        connection.on('close', function (err) {
          logger.error('mysqldb conn close');
          connectionState = false;
        });
        connection.on('error', function (err) {
          logger.error('mysqldb error: ' + err);
    
          if (!err.fatal) {
            //throw err;
          }
          if (err.code !== 'PROTOCOL_CONNECTION_LOST') {
            //throw err;
          } else {
            connectionState = false;
          }
    
        });
      }
    }
    attemptConnection(connection);
    
    var dbConnChecker = setInterval(function(){
      if(!connectionState){
        logger.info('not connected, attempting reconnect');
        attemptConnection(connection);
      }
    }, conf.db.checkInterval);
    
    // Mysql query wrapper. Gives us timeout and db conn refreshal! 
    var queryTimeout = conf.db.queryTimeout;
    var query = function(sql,params,callback){
      if(connectionState) {
        // 1. Set timeout
        var timedOut = false;
        var timeout = setTimeout(function () {
          timedOut = true;
          callback('MySQL timeout', null);
        }, queryTimeout);
    
        // 2. Make query
        connection.query(sql, params, function (err, rows) {
          clearTimeout(timeout);
          if(!timedOut) callback(err,rows);
        });
      } else {
        // 3. Fail if no mysql conn (obviously)
        callback('MySQL not connected', null);
      }
    }
    
    // And we present the same interface as the node-mysql library!
    // NOTE: The escape may be a trickier for other libraries to emulate because it looks synchronous
    exports.query = query;
    exports.escape = connection.escape;
    

提交回复
热议问题