mysql - 如何监控节点中的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);
});
有两个部分让我感到困惑,
connection.connect() 是真正的连接吗?我看到它正在检查错误。但是如果一切正常会发生什么,但是我在 5 分钟后关闭了 mysql 服务器,请问如何监控状态?即使对于池事件,我也看不到断开连接事件。
对于上面的代码,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 中解释了所有内容,请阅读我
推荐阅读
- r - GGplot 未在 RStudio 上显示
- laravel - Laravel Nova:替换主路由并作为默认应用程序运行
- python - 计算检测到的对象像素数占图片总像素数的百分比
- swift - 使用 Any 而不是泛型
- docker - 如何配置 docker-compose 卷访问权限
- database - MongoDB WiredTiger 是否使用聚集索引?
- android - Kotlin,警报管理器不触发
- javascript - 如何使用 JavaScript 更改对象中的项目以替换 Firebase 不接受的特殊字符
- android - 如何从 SQLite 数据库中检索声音?
- mysql - MySQL:计算列中的宽度日期