简体   繁体   English

如何监控节点中的mysql连接状态?

[英]How to monitor mysql connection status in node?

So this is from https://www.npmjs.com/package/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);
});

there're 2 parts confuse me,有两个部分让我感到困惑,

  1. is connection.connect() making the real connection? connection.connect() 是真正的连接吗? i see it's checking for error.我看到它正在检查错误。 But what happens if everything is ok, but i turn off mysql server after 5 minutes, how to monitor the status pls?但是如果一切正常,我会在 5 分钟后关闭 mysql 服务器,请问如何监控状态? Even for pool events, i don't see the disconnect event.即使对于池事件,我也看不到断开连接事件。

  2. for the above code, is there a async/await version for connection.connect()?对于上面的代码,connection.connect() 是否有异步/等待版本?

Thanks !谢谢 !

connection.connect is sync you can use it after connection. connection.connect 是同步的,您可以在连接后使用它。 To handle connection errors you can use:要处理连接错误,您可以使用:

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

By the way everything is explained in node-mysql read me顺便说一句, node-mysql 中解释了所有内容,请阅读我

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

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