如何确保在MonogDB连接断开后Node.js继续运行?

 allmon白_980 发布于 2023-02-09 10:11

我在Express中有一个错误处理middlware,试图捕获所有传入的错误:

app.use(function(err, req, res, next){
  console.error(err.stack);
  res.status(500);
  res.render('500.jade');
});

但由于某些原因,每当我关闭mongod进程时,我的应用程序崩溃时会出现以下堆栈跟踪:

Error: failed to connect to [localhost:27017]
    at null. (//node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/server.js:540:74)
    at EventEmitter.emit (events.js:106:17)
    at null. (//node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/connection_pool.js:140:15)
    at EventEmitter.emit (events.js:98:17)
    at Socket. (//node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/connection.js:478:10)
    at Socket.EventEmitter.emit (events.js:95:17)
    at net.js:441:14
    at process._tickCallback (node.js:415:13)

Process finished with exit code 8

我尝试使用以下配置,但它没有帮助我:

var options = {
  server:{
    auto_reconnect: true,
      poolSize: 10,
      socketOptions:{
      keepAlive: 1
    }
  },
  db: {
    numberOfRetries: 10,
    retryMiliSeconds: 1000
  }
}

mongoose.connect(config.db, options);

有人可能会想知道"如果没有数据库连接它的基本上不再运行,你为什么要让你的应用程序运行?".我不希望它崩溃并重新启动.在一定次数的尝试之后,Supervisor和Forever模块似乎停止尝试重新连接,从而使您的应用程序处于崩溃状态.

理想情况下,当MongoDB崩溃时,我想向用户显示500.jade错误页面,同时服务器应该每隔10秒继续尝试重新连接到数据库.重新连接后,恢复所有正常操作.

编辑:以下发布的解决方案都没有为我工作,域名除外.

1 个回答
  • 这就是我处理Mongo失败的方法 - 将其添加为中间件.它还会尝试重新连接.

    // Handler in case Mongo  goes down
    app.use(function(req, res, next) {
      // We lost connection!
      if (1 !== mongoose.connection.readyState) {
    
        // Reconnect if we can
        mongoose.connect(config.db, options);
        res.status(503);
        throw new Error('Mongo not available');
      }
      next();
    
    });
    

    这假设您在某处有一个标准的50x错误处理程序,它将向用户显示一个不错的页面.

    重新连接用于下一个用户/页面加载,以检查它是否已备份.工作得很好.

    2023-02-09 10:12 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有