如何监视节点中的mysql连接状态?
这是来自,
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'example',
user : 'bob',
password : 'secret'
});
connection.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected as id ' + connection.threadId);
});
有两个部分使我感到困惑,
是connection.connect()建立真正的连接吗?我看到它正在检查错误。但是,如果一切正常,会发生什么,但是5分钟后我关闭mysql服务器,如何监视状态pls?即使对于池事件,我也看不到断开连接事件。
对于上面的代码,是否有用于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 read me中的所有内容进行解释