【问题标题】:NodeJS + Mongoose timeout on connectionNodeJS + Mongoose 连接超时
【发布时间】:2012-03-12 06:22:24
【问题描述】:

所以我读到 mongoose driver 用于 NodeJS 缓存查询,直到它连接到 MongoDB(没有超时)。但是当数据库崩溃时,应该可以向用户发送消息。那么让我们看看这段NodeJS代码:

Users.find({}, function(err, result) {
  // Do something with result and send response to the user
});

这可能挂在 infintum 上。因此,解决此问题的一种方法是执行以下操作

var timeout = setTimeout(function() {
  // whem we hit timeout, respond to the user with appropriate message
}, 10000);

Users.find({}, function(err, result) {
  clearTimeout(timeout);  // forget about error
  // Do something with result and send response to the user
});

问题是:这是一个好方法吗?内存泄漏(挂起查询到 MongoDB)怎么办?

【问题讨论】:

    标签: javascript node.js mongodb timeout mongoose


    【解决方案1】:

    我希望我能正确理解你的问题,我想你会担心,因为 mongoose 采用乐观模式,让你理所当然地认为它最终会连接,你担心你将无法连接连接失败时优雅处理。

    Connection.open() 方法接受回调作为最后一个参数。如果无法打开连接,将使用 Error 对象作为参数调用此回调。来自猫鼬的源(端口和选项是可选的):

    Connection.prototype.open = function (host, database, port, options, callback)
    

    或者,您可以订阅 Connection 的“错误”事件。它还接收错误对象作为参数。但是,只有在所有参数(和状态)都有效时才会发出它,而每次都会调用回调,即使在实际连接尝试之前出现问题(例如连接未处于就绪状态),即使连接成功(在这种情况下错误参数为空)。

    【讨论】:

    • 快到了。但我真正需要的是以下内容:我的服务器连接到数据库。一段时间后,数据库崩溃,当用户使用Users.save(...) 调用视图时,连接挂起。所以现在我想抓住那个数据库连接失败了。每次与数据库交互时,我总是可以重新连接(并且在回调时做其他事情),但这似乎并不优雅。
    【解决方案2】:

    我通过在我使用 DB 的每个路由器中添加一个额外的步骤来解决这个问题。

    它有点乱,但它可以工作并且 100% 没有泄漏。

    类似这样的:

    // file: 'routes/api/v0/users.js'
    router
    var User = require('../../../models/user').User,
        rest = require('../../../controllers/api/v0/rest')(User),
        checkDB = require('../../../middleware/checkDB');
    
    module.exports = function (app) {
      app.get('/api/v0/users', checkDB, rest.get);
      app.get('/api/v0/users/:id', checkDB, rest.getById);
      app.post('/api/v0/users', checkDB, rest.post);
      app.delete('/api/v0/users', checkDB, rest.deleteById);
      app.put('/api/v0/users', checkDB, rest.putById);
    };
    
    // file: 'middleware/checkDB.js'
    var HttpError = require('../error').HttpError,
        mongoose = require('../lib/mongoose');
    
    // method which checks is DB ready for work or not
    module.exports = function(req, res, next) {
      if (mongoose.connection.readyState !== 1) {
        return next(new HttpError(500, "DataBase disconnected"));
      }
      next();
    };
    

    PS 如果您知道更好的解决方案,请告诉我。

    【讨论】:

      猜你喜欢
      • 2017-12-18
      • 1970-01-01
      • 2014-10-10
      • 2021-01-12
      • 1970-01-01
      • 2017-06-29
      • 2017-03-27
      • 1970-01-01
      • 2017-12-29
      相关资源
      最近更新 更多