我使用带有mysql的节点js,并希望避免应用程序在连接错误时崩溃。现在我使用这个:
function mysql_handleDisconnect() {
mysql_connection = mysql.createConnection(mysql_config_obj); // Recreate the connection, since
// the old one cannot be reused.
mysql_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);
mysql_handleDisconnect(); // 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.
mysql_connection.on('error', function(err) {
console.log('db error', err);
if(err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usually
mysql_handleDisconnect(); // lost due to either server restart, or a
} else { // connnection idle timeout (the wait_timeout
throw err; // server variable configures this)
}
});
}
mysql_handleDisconnect(mysql_connection);
所以这是阻塞,因为如果连接关闭它会导致热循环。我的问题是,如果我每隔2秒添加一个setTimeout重新建立连接,当我用“mysql_connection.query”进行查询时,我可能会遇到致命错误( 'SELECT ...')“。在这种情况下,应用程序崩溃。
所以我的问题是,如果在我进行查询之前有可能检查连接?
在做任何事情之前,尝试在每个微服务中使用以下代码:
if(connection.state === 'disconnected'){
return respond(null, { status: 'fail', message: 'server down'});
}
我知道这是一个老问题,但我发现connection.ping( (err) => {...})
对负载平衡器和诸如此类的健康检查非常有用。