有没有办法解决 node.js 中的 mysql 重新连接问题? [英] Is there a way to fix the mysql reconnection issue in node.js?
问题描述
您好,在调用 mysql 服务器时,如果连接由于长时间未使用而未打开/断开连接,那么当我尝试重新连接时,它会给我一个错误.我查过这个错误,但在我的情况下,这些回应似乎对我没有帮助.这是错误:在已经将握手入队后无法入队握手.这是导致此问题的代码:
Hello when making calls to the mysql server if the connection is not open/disconnected due to a long time of not using it then it will give me an error when I attempt to Re-Connect. I have looked this error up but the responses don't seem to help me in my situation. Here is the error: Cannot enqueue Handshake after already enqueuing a Handshake. Here is the code causing this:
var con = mysql.createConnection({
host: "",
user: "",
password: "",
database: ""
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
con.on('error', function(err) {
console.log(err);
console.log('MYSQL Disconnected');
})
if (con.state == 'disconnected') {
con.connect(function(err) {
if (err) throw err;
});
}
下面有更多代码,但无关紧要,因为它会检查身份验证状态并进行查询
More code is below but is irrelevant due to it checking for authenticated state and querying
推荐答案
我发现 mysql.createConnection
和 mysql.createPool
之间的区别在于前者与MySQL(超时),我需要重新启动节点服务器以重新建立连接.使用创建池,应用程序仅在需要时使用 mysql 连接,并且当 MySQL 超时时我不需要重新启动节点.
The difference I found between mysql.createConnection
and mysql.createPool
is when the former lost connection to MySQL (timeout), I need to restart the node server to re-establish connection. With create pool, the app only uses mysql connection when it's required and when MySQL timeout I don't need to restart the node.
试试这个,看看有没有好处:
Try this and see if there's any good:
dbConnectionInfo = {
host: "",
user: "",
password: "",
database: ""
};
var con = mysql.createPool(
dbConnectionInfo
);
con.on('connection', function (connection) {
console.log('DB Connection established');
connection.on('error', function (err) {
console.error(new Date(), 'MySQL error', err.code);
});
connection.on('close', function (err) {
console.error(new Date(), 'MySQL close', err);
});
});
这个方法是我从一个帖子中找到的,但我不记得是哪个,因为我见过很多 mysl.createPool
.您可以在此处找到更多方法
This method I found from a post but I can't remember which one because there are a lot of mysl.createPool
I've seen. You may find more methods here
这篇关于有没有办法解决 node.js 中的 mysql 重新连接问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!