【问题标题】:Mongoose - useDb(name) not allowing more than 10 concurrent requestMongoose - useDb(name) 不允许超过 10 个并发请求
【发布时间】:2014-10-07 15:56:26
【问题描述】:

我们正在使用 mongoose 连接到 MongoDB。最初创建了一个包含 100 个连接的池,并使用 mongoose 方法 useDb

连接到其他一些数据库

下面是代码sn-p

var url = require("url");
var connectRoute = require('connect-route');
var connect = require('connect'),
    app = connect.createServer();

var mongoose = require('mongoose');
 var conn = mongoose.createConnection('mongodb://localhost:10040/first', {server: {poolSize: 100}});

 conn.on('error', console.error.bind(console, 'connection error:'));

 var Schema = mongoose.Schema;
 var MySchema = new Schema({
 user: String,
 pwd: String, roles: []
 },
 {strict: false}
 );
app.use(connectRoute(function (router){
    router.get('/get', function(req,res){
        var db2 = conn.useDb('second_DB');
        var data = db2.model('', MySchema, 'coll');
        data.update({name: "Janu"}, {$set: {"name": "test"}}, {upsert: true} , function (err, data,log) {
            //console.log(a.data.data );
            res.end(JSON.stringify(log.connectionId));
        });
    });
}));

app.listen(3000);
console.log('info','Connect server listening on port 3000 ' );

即使 Poolsize 设置为 100 ,当超过 10 个并发请求时抛出警告为

(node) 警告:检测到可能的 EventEmitter 内存泄漏。增加了 11 位听众。使用emitter.setMaxListeners() 增加限制。

MongoDB 版本 - 2.6.4 猫鼬版 - 3.8.12

谁能帮忙解释为什么会出现这个警告??

【问题讨论】:

  • 使用 useDb 方法时会抛出警告。除此之外,没有其他方法会引发警告。当我在上面的代码 sn-p 中注释行 var db2 = conn.useDb('second_DB') 时没有收到警告。
  • 您找到解决方案了吗?

标签: node.js mongodb


【解决方案1】:

函数conn.useDb 创建一个新的连接对象并在其上添加一个事件监听器。 Poolsize 的大小对此没有影响。

您的代码实际上存在 EventEmitter 内存泄漏。每次调用路由时,都会创建一个带有事件监听器的新对象,并且永远不会被删除。

解决您的问题:缓存 conn.useDb 的返回值。

如果你有超过 10 个数据库,你可以在应用程序启动时增加监听器的限制:

require('events').EventEmitter.defaultMaxListeners = 15;

或与

emitter.setMaxListeners()

【讨论】:

    【解决方案2】:

    useDb('name', {noListener:true} ); 时使用该选项

    【讨论】:

    【解决方案3】:

    您可能希望设置the useCache option 以便每个useDb 调用都不会创建新的连接对象。

    【讨论】:

      【解决方案4】:

      使用useDb()时使用以下dbOptions

      const useDbOptions = {
          //ensures connections to the same databases are cached
          useCache: true,
          //remove event listeners from the main connection
          noListener: true
      }
          
      conn.useDb('another_DB', useDbOptions);
      

      还要确保在每次请求后手动从每个连接中删除所有用户模型,使用:

       conn.deleteModel(/.*/) // Delete all models on conn
      

      这样可以确保释放多余的内存,因为否则每个连接都会维护与特定连接关联的所有模型的内部列表。

      请参阅:https://github.com/Automattic/mongoose/issues/9961 了解详细信息。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-12-20
        • 2017-01-04
        • 1970-01-01
        • 2017-03-15
        • 1970-01-01
        • 2013-11-22
        • 1970-01-01
        相关资源
        最近更新 更多