连接丢失:服务器关闭了连接
使用 node_modules mysql 使用 Node.js。我已经安装了 npm 的 nodemon 模块来持续监控我的 node.js 应用程序,并在服务器崩溃时重新启动服务器,当服务器崩溃时,应用程序不会自行重新启动。
在搜索了很多网站和实施代码后,我已经成功解决了上述错误。为此,我使用了 mysqlpool。代码如下和描述。
首先,您声明这样的连接:
var mysql = require('mysql');
var mysqlPool = mysql.createPool({
host : "localhost",
user : "username",
password: "password",
database :"databasename",
port:3306
});
现在您的连接配置已成功创建和使用,如下所示:
var strQuery = "SELECT * FROM userdetails"; //here store sql query in strQuery variable.
mysqlPool.getConnection(function(err, connection) {
if(err) throw err;
connection.query(strQuery, function(err, rows) {
if(err) {
// if error occures goes here.
connection.end(); // if error occured closed the connection
console.error(err);
return;
}
//If no error here you get your query output.
console.log(rows[0].User_name); //retrieved username & print into console log or you can also retrived any rows like this.
connection.end();// After performing the operation then closed the connection.
});
});
只有在任何模块或文件中进行任何更改时,Nodemon 才会重新启动应用程序!
这可能与wait_timeout
服务器变量有关。当在这么多秒内没有数据通过连接时,服务器将断开连接。您可以提高设置,但您可能会面临需要处理更多空闲连接的风险,最终您将再次遇到超时。
最好的解决方案是在发生这种情况时重新建立客户端连接,这似乎不支持开箱即用,但您可以自己实现:https://www.exratione。 com/2013/01/nodejs-connections-will-end-close-and-otherwise-blow-up/
另一种解决方案可能是定期(在超时之前)做一个简单的查询,比如SELECT 1
保持你的连接活跃。