4月 272014
 

node.js项目中有个项目发现运行一段时间后总会自动关闭,查看输出日志会看到下面的输出: error Caught exception: Error: Connection lost: The server closed the connection.  原来使用的node-mysql模块在mysql连接timeout或出现异常情况下默认是没有重连机制的,可以用下面的类似代码解决:

  var db;

  function handleConnect() {
    db = mysql.createConnection({
      host     : config.mysql.host,
      user     : config.mysql.user,
      password : config.mysql.password,
      database : config.mysql.database
    }); // Recreate the connection, since the old one cannot be reused.

    db.connect(function(err) {              // The server is either down
      if(err) {                                     // or restarting (takes a while sometimes).
        console.log(‘error when connecting to db:’, err);
        setTimeout(handleConnect, 2000); // We introduce a delay before attempting to reconnect,
      }                                     // to avoid a hot loop, and to allow our node script to
    });                                     // process asynchronous requests in the meantime.
                                            // If you’re also serving http, display a 503 error.
    db.on(‘error’, function(err) {
      console.log(‘db error’, err);
      if(err.code === ‘PROTOCOL_CONNECTION_LOST’) { // Connection to the MySQL server is usually
        handleConnect();                         // lost due to either server restart, or a
      } else {                                      // connnection idle timeout (the wait_timeout
        throw err;                                  // server variable configures this)
      }
    });
  }

  handleConnect();

Sorry, the comment form is closed at this time.