簡體   English   中英

如何監控節點中的mysql連接狀態?

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

所以這是來自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() 是否有異步/等待版本?

謝謝 !

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 中解釋了所有內容,請閱讀我

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM