Mysql Node.Js-错误:连接丢失:服务器已关闭连接
两周前,作为我新工作的一部分,我部署了我的第一个应用程序(Woo-Hoo!:),但自从我部署了它之后,每天晚上,应用程序都会崩溃。 服务器端是用Node.js构建的,我使用XAMPP和MYSQL来运行数据库。 这就是我不断得到的错误: 我正在搜索解决方案,发现以下代码:Mysql Node.Js-错误:连接丢失:服务器已关闭连接,mysql,node.js,server,xampp,connection,Mysql,Node.js,Server,Xampp,Connection,两周前,作为我新工作的一部分,我部署了我的第一个应用程序(Woo-Hoo!:),但自从我部署了它之后,每天晚上,应用程序都会崩溃。 服务器端是用Node.js构建的,我使用XAMPP和MYSQL来运行数据库。 这就是我不断得到的错误: 我正在搜索解决方案,发现以下代码: var connection; function handleDisconnect() { connection = mysql.createConnection(con); // Recreate the conne
var connection;
function handleDisconnect() {
connection = mysql.createConnection(con); // 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();
我将此代码粘贴在createConnection函数之后:
var con = mysql.createConnection({
host: "EXAMPLE FOR STUCK OVER FLOW",
user: "EXAMPLE FOR STUCK OVER FLOW",
password: "EXAMPLE FOR STUCK OVER FLOW",
database: "EXAMPLE FOR STUCK OVER FLOW"
});
我将非常感谢你的建议
谢谢 新代码现在起作用了吗?在MySQL协议\连接\丢失错误的情况下尝试建立新连接的那个?在我看来,我们可以在这里使用MySQL池。它将踢出一个死连接,并在请求时创建一个新连接。因此,您不需要像上面那样编写手动断开连接的代码。让模块为您完成这项艰巨的工作。参考:你好,surajs21!谢谢你的帮助!代码正在运行,但在夜间会不断崩溃。我正在读你发来的东西,但我不完全确定我是否理解。让我试着在结尾复制一下。我怀疑当我们要创建一个干净的新连接以防出现错误时,我们还应该使用
connection.destroy()关闭以前的连接代码>。但让我先试试。