首页 > 解决方案 > 如何监控节点中的mysql连接状态?

问题描述

所以这是来自https://www.npmjs.com/package/mysql

var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : 'example.org',
  user     : 'bob',
  password : 'secret'
});

connection.connect(function(err) {
  if (err) {
    console.error('error connecting: ' + err.stack);
    return;
  }

  console.log('connected as id ' + connection.threadId);
});

有两个部分让我感到困惑,

  1. connection.connect() 是真正的连接吗?我看到它正在检查错误。但是如果一切正常会发生什么,但是我在 5 分钟后关闭了 mysql 服务器,请问如何监控状态?即使对于池事件,我也看不到断开连接事件。

  2. 对于上面的代码,connection.connect() 是否有异步/等待版本?

谢谢 !

标签: mysqlnode.js

解决方案


connection.connect 是同步的,您可以在连接后使用它。要处理连接错误,您可以使用:

function handleDisconnect() {
  connection = mysql.createConnection(db_config); // Recreate the connection, since
                                                  // the old one cannot be reused.

  connection.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(handleDisconnect, 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.
  connection.on('error', function(err) {
    console.log('db error', err);
    if(err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usually
      handleDisconnect();                         // lost due to either server restart, or a
    } else {                                      // connnection idle timeout (the wait_timeout
      throw err;                                  // server variable configures this)
    }
  });
}

顺便说一句,node-mysql 中解释了所有内容,请阅读我


推荐阅读