所以这是来自 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);
});
有两部分让我感到困惑,
connection.connect(( 是真正的连接吗? 我看到它正在检查错误。但是如果一切正常,但是我在 5 分钟后关闭了 mysql 服务器,会发生什么,如何监控状态? 即使对于池事件,我也看不到断开连接事件。
对于上面的代码,connection.connect(( 是否有 async/await 版本?
谢谢!
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)
}
});
}
顺便说一下,一切都在节点-mysql 中解释过 自读我