在我当前正在处理的Node.js项目中,mysql服务器在一段时间闲置后关闭了连接。我实现了一个错误处理程序,该错误处理程序在这种连接丢失后会重新连接。错误处理有效,但是在使用新连接之前,我找不到一种方法来获取需要连接的文件。
我已经尝试删除缓存,但这不能解决我的问题。
var mysql = require('mysql');
var mysqlConfig = require('./mysqlConfig');
var connection;
function handleDisconnect() {
connection = mysql.createConnection(mysqlConfig.db);
connection.connect((err) => {
if (err) {
console.log("error on connection to Database: " + err);
setTimeout(handleDisconnect, 1000);
}
});
connection.on('error', (err) => {
delete require.cache[require.resolve('./db.js')]; //this module
if (err.code === 'PROTOCOL_CONNECTION_LOST') {
handleDisconnect();
} else {
throw err;
}
});
}
handleDisconnect();
module.exports = connection;
以下是其中需要此模块的文件示例:
var db = require('../db');
var connector = {};
connector.GetStuff = function(query) {
return new Promise((resolve, reject) => {
let response = {};
db.query(query, (error, results, fields) => {
if (error) throw error;
if (results && results.length > 1) {
response = results[0];
resolve(response);
}
})
})
}
Id只是替换连接对象,而以前需要用新的对象。但是实际上我的应用程序因以下错误而崩溃:
Error: Cannot enqueue Query after fatal error.
请不要告诉我只是为每个查询打开一个新连接。这是我出于客户期望而无法使用的概念。
答案 0 :(得分:2)
一个好的解决方案是不导出第一个文件中的连接对象,而是导出一些包装器或容器,这些包装器或容器的内容由连接故障处理程序功能定期更新。
class ConnectionContainer {
setConnection(connection) {
this.connection = connection;
}
getCurrentConnection() {
return this.connection;
}
}
const connectionContainer = new ConnectionContainer();
function handleDisconnect() {
const connection = mysql.createConnection(mysqlConfig.db);
connection.connect((err) => {
if (err) {
console.log("error on connection to Database: " + err);
return setTimeout(handleDisconnect, 1000);
} else {
container.setConnection(connection); // set a new connection once it's connected
}
});
connection.on('error', (err) => {
delete require.cache[require.resolve('./db.js')]; // I don't think you need this anymore
if (err.code === 'PROTOCOL_CONNECTION_LOST') {
handleDisconnect();
} else {
throw err;
}
});
}
handleDisconnect();
module.exports.connectionContainer = connectionContainer;
// and in the connector file you could go like this:
const { connectionContainer } = require('../db'); // you might need a better name here for the file
//...
connectionContainer.getCurrentConnection().query(query, () => {});