【发布时间】:2018-02-25 20:43:48
【问题描述】:
我正在使用以下代码将我的节点连接到 mysql,用于我在项目中使用的所有其余 API; 我已将此作为我所有查询请求的通用数据库连接文件。
var mysql = require('mysql');
var db_connect = (function () {
function db_connect() {
mysqlConnConfig = {
host: "localhost",
user: "username",
password: "password",
database: "db_name"
};
}
db_connect.prototype.unitOfWork = function (sql) {
mysqlConn = mysql.createConnection(mysqlConnConfig);
try {
sql(mysqlConn);
} catch (ex) {
console.error(ex);
} finally {
mysqlConn.end();
}
};
return db_connect;
})();
exports.db_connect = db_connect;
上面的代码工作正常,我将使用我的查询在我的所有 rest api 中使用下面的“sql”来执行,如下所示。
var query1 = "SELECT * FROM table1";
sql.query(query1,function(error,response){
if(error){
console.log(error);
}
else{
console.log(response);
}
})
到目前为止一切都很好,但问题是我收到 sql 协议连接错误 在运行我的永久模块 8-12 小时后
forever start app.js
我正在使用上述永久模块开始我的项目。 8-12 小时后,我收到以下错误,我所有的其余 api 都无法正常工作或出现故障。
"stack": ["Error: Connection lost: The server closed the connection.", " at Protocol.end (/path/to/my/file/node_modules/mysql/lib/protocol/Protocol.js:109:13)", " at Socket.<anonymous> (/path/to/my/file/node_modules/mysql/lib/Connection.js:102:28)", " at emitNone (events.js:72:20)", " at Socket.emit (events.js:166:7)", " at endReadableNT (_stream_readable.js:913:12)", " at nextTickCallbackWith2Args (node.js:442:9)", " at process._tickDomainCallback (node.js:397:17)"],
"level": "error",
"message": "uncaughtException: Connection lost: The server closed the connection.",
"timestamp": "2017-09-13T21:22:25.271Z"
然后我在研究中得到了一个解决方案来配置手柄断开连接,如下所示。 但我正在努力使用我的代码配置我的 sql 连接,如下所示。
var db_config = {
host: 'localhost',
user: 'root',
password: '',
database: 'example'
};
var connection;
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)
}
});
}
handleDisconnect();
谁能帮我用上面的代码修改我的代码?
【问题讨论】: