2013-10-14 139 views
5

我在Node.js服务器上运行一个Web应用程序,我需要它始终在线,所以我永远在使用。但这是一段时间后我得到的:Node.js - 服务器关闭了连接?

Error: Connection lost: The server closed the connection. 
    at Protocol.end (/home/me/private/app/node_modules/mysql/lib/protocol/Protocol.js:73:13) 
    at Socket.onend (stream.js:79:10) 
    at Socket.EventEmitter.emit (events.js:117:20) 
    at _stream_readable.js:910:16 
    at process._tickCallback (node.js:415:13) 
error: Forever detected script exited with code: 8 
error: Forever restarting script for 3 time 

我有两台服务器已连续运行了大约10天。我在所有的服务器上都有一个“keepalive”循环,每隔5分钟左右做一个“select 1”mysql查询,但看起来没有任何区别。

任何想法?

编辑1个

我的其他服务器都给人一种类似的错误,我认为这是“连接超时”,所以我把这个功能:

function keepalive() { 
    db.query('select 1', [], function(err, result) { 
     if(err) return console.log(err);  
     console.log('Successful keepalive.'); 
    }); 
} 

它固定我的其他两个服务器。但在我的主服务器上,我仍然遇到上述错误。

这里是我怎样,我开始我的主服务器:

var https = require('https'); 
https.createServer(options, onRequest).listen(8000, 'mydomain.com'); 

我不知道什么样的代码是你在看到感兴趣。基本上服务器是一个REST API,它需要一直保持。它大约有2-5个,也许每分钟有10个请求。

+0

它看起来像你的应用程序脚本有一些错误。尝试运行'节点app.js'而不是永远看到错误。 – Sriharsha

+0

在日志中没有可见的错误,我试着用node-dev运行它。这是我看到的唯一错误消息。 –

+0

让我们更多地了解您的应用,以便了解发生了什么。你留下一个套接字打开MySQL?为什么?它是一个远程数据库吗? – TheBronx

回答

13

错误与您的HTTPS实例无关,它与您的MySQL连接有关。

到数据库的连接意外结束并且未被处理。要解决此问题,可以使用手动重新连接解决方​​案,也可以使用自动处理重新连接的连接池。

以下是从node-mysql的文档中摘取的手动重新连接示例。

var db_config = { 
    host: 'localhost', 
    user: 'root', 
    password: '', 
    database: 'example' 
}; 

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(); 
+0

对不起,延迟回复。我刚刚用您的答案替换了我的代码,并启动了服务器。我们明天应该知道它是否有效:)干杯 –

+0

它工作?还有,@hexacyanide,为什么甚至需要这个想法?为什么MySql连接偶尔会不知所措? –

+2

我刚刚第一次遇到这个错误。经过数月的正常运行时间后,MySQL连接突然不可用。事实证明,我安装了一个名为“无人参与升级”的软件包,它安排了一个自动应用的MySQL安全更新,从而导致MySQL服务器重新启动。 –

相关问题