javascript – Node.js – 服务器关闭连接?

前端之家收集整理的这篇文章主要介绍了javascript – Node.js – 服务器关闭连接?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我在Node.js服务器上运行一个Web应用程序,我需要它一直在线,所以我一直在使用.但这是我经过一段时间后得到的:

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

我还有两台服务器连续运行了大约10天.我在所有服务器上都有一个“keepalive”循环,每5分钟左右进行一次“select 1”mySQL查询,但似乎没有任何区别.

有任何想法吗?

编辑1

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

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

它修复了我的另外两台服务器.但在我的主服务器上,我仍然得到上面的错误.

这是我如何启动我的主服务器:

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

我不确定你有兴趣看到什么代码.基本上,服务器是一个REST API,它需要一直保持高效.它每分钟大约需要2-5个,也许10个请求.

最佳答案
错误与您的HTTPS实例无关,它与您的MysqL连接有关.

数据库的连接意外结束,未进行处理.要解决此问题,您可以使用手动重新连接解决方​​案,也可以使用自动处理重新连接的连接池.

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

  1. var db_config = {
  2. host: 'localhost',user: 'root',password: '',database: 'example'
  3. };
  4. var connection;
  5. function handleDisconnect() {
  6. connection = MysqL.createConnection(db_config); // Recreate the connection,since
  7. // the old one cannot be reused.
  8. connection.connect(function(err) { // The server is either down
  9. if(err) { // or restarting (takes a while sometimes).
  10. console.log('error when connecting to db:',err);
  11. setTimeout(handleDisconnect,2000); // We introduce a delay before attempting to reconnect,} // to avoid a hot loop,and to allow our node script to
  12. }); // process asynchronous requests in the meantime.
  13. // If you're also serving http,display a 503 error.
  14. connection.on('error',function(err) {
  15. console.log('db error',err);
  16. if(err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MysqL server is usually
  17. handleDisconnect(); // lost due to either server restart,or a
  18. } else { // connnection idle timeout (the wait_timeout
  19. throw err; // server variable configures this)
  20. }
  21. });
  22. }
  23. handleDisconnect();

猜你在找的MySQL相关文章