Node.js和MYSQL句柄断开连接

时间:2014-05-07 11:56:08

标签: mysql node.js

我从网络搜索中得到以下代码,可以从客户端连接并从数据库返回数据确定。

这是在家中的Mac上设置的。如果我失去了互联网连接(通常重新启动路由器以获得更快的连接),它恢复正常。但是,如果连接断开一段时间我仍然有我的node.js工作,但MYSQL连接已经死了。我必须停止并启动node.js以重新建立连接。

var db_config = {
host     : 'www.xxxx.com',
user     : 'xxx',
password : 'xxx',
};
var connection;

function handleDisconnect() {
connection = mysql.createConnection(db_config); // 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();

确保连接恢复的最佳方法是什么?

MrWarby。

0 个答案:

没有答案