[英]NodeJS MySQL, reconnecting on connection loss?
function Connect() {
var connection = mysql.createConnection({
host : 'hidden',
user : 'hidden',
password : 'hidden',
database : 'hidden'
});
connection.connect(function(err) {
if (err) {
console.log('Error connecting to Database'.red);
setInterval(Connect, 5000);
connection.end();
}else{
console.log('Connected to Database'.green);
}
});
}
Connect();
I am attempting to make it so my code won't crash if the database loses connection.我正在尝试做到这一点,这样如果数据库失去连接,我的代码就不会崩溃。
It will be connected to a database which is prone to many restarts and updates, meaning that the program will crash upon losing connection.它将连接到一个容易重启和更新的数据库,这意味着程序将在失去连接时崩溃。
I tried adding setInterval(Connect, 5000);
我尝试添加setInterval(Connect, 5000);
so it would attempt to reconnect if it loses connection but to no luck.因此,如果它失去连接但没有运气,它会尝试重新连接。
Can someone help me out where I am going wrong?有人可以帮我解决我哪里出错了吗?
Assuming you're using the mysql
npm package you can use connection pooling provided by the library:假设您使用的是mysql
npm package,您可以使用库提供的连接池:
https://github.com/mysqljs/mysql#pooling-connections https://github.com/mysqljs/mysql#pooling-connections
When a previous connection is retrieved from the pool, a ping packet is sent to the server to check if the connection is still good.当从池中检索到先前的连接时,会向服务器发送一个 ping 数据包以检查连接是否仍然良好。
It's rather easy to use, instead of using createConnection
you can use createPool
它相当容易使用,而不是使用createConnection
你可以使用createPool
var pool = mysql.createPool({
connectionLimit : 2,
host : 'example.org',
user : 'bob',
password : 'secret',
database : 'my_db'
});
And then use the pool to query the database.然后使用池查询数据库。
It has many additional benefits as well eg load balancing connections.它还有许多额外的好处,例如负载平衡连接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.