之前写的nodeJs项目,用到了MySQL数据库,在本地测试均没神马问题。放上服务器运行一段时间后,偶然发现打开页面的时候页面一直处于等待状态,直到Nginx返回超时错误。于是上服务器检查了遍,发现程序仍然在运行,且能正确记录每次的请求,再修改代码跟踪调试,原来是在查询数据库的时候,回调一直没有被执行,程序就挂在那里了。
MySQL中有一个名叫wait_timeout的变量,表示操作超时时间,当连接超过一定时间没有活动后,会自动关闭该连接,这个值默认为28800(即8小时)。
在网上找的解决方法有两种(本人推荐第二种):
第一种是利用 err.code === 'PROTOCOL_CONNECTION_LOST'
监听是否断开状态 如果断开了重新链接
function handleError (err) {
if (err) {
// 如果是连接断开,自动重新连接
if (err.code === 'PROTOCOL_CONNECTION_LOST') {
connect();
} else {
console.error(err.stack || err);
}
}
}
// 连接数据库
function connect () {
db = mysql.createConnection(config);
db.connect(handleError);
db.on('error', handleError);
}
var db;
connect();
第二种是使用pool启用连接池:
createPool
var mysql = require('mysql');
var pool = mysql.createPool(config);
pool.getConnection(function(err, connection) {
// Use the connection
connection.query( 'SELECT something FROM sometable', function(err, rows) {
// And done with the connection.
connection.end();
// Don't use the connection here, it has been returned to the pool.
});
});
标签: 前端front服务器nodeJs