node js cluster mongoose connection

时间:2014-07-21 05:27:52

标签: node.js mongodb mongoose

我在我的应用程序mongodb(未分片)中使用了内置集群模块的nodejs 每个集群(工作者)连接中的存储使用mongoose.createConnection方法进行,并在插入数据后关闭。

但我期待的是,无论何时发出请求,它都会打开与数据库和进程请求的连接并关闭连接。

但是我注意到当我检查mongodb日志时仍然打开连接并且它的数量比处理器/(群集节点)的数量大得多。

并且我把poolSize:1,autreconect:false,即使在调用close()方法之后,仍然有些连接没有关闭。

我的观察是当连接错误发生时连接未关闭 请帮帮我

我正在使用以下脚本来获取连接。

module.exports.getDb = function () {

    var dburl = 'mongodb://localhost/DB';


    db = mongoose.createConnection(dburl, {
        server: {
            socketOptions: {
                keepAlive: 1,
                connectTimeoutMS: 30000
            },
            auto_reconnect: false,
            poolSize: 1

        }

    }, function (err) {

        console.log(err)
    });

    db.on('error', function (err) {
        console.log(err + " this is error");
        db.close();
    });

    return db;

}

我在evey查询回调结束时使用db.close()关闭连接。

1 个答案:

答案 0 :(得分:0)

你在找这样的东西吗?

db.connection.on('error', function (e) {
  console.log(e + " this is error");
  db.close();
});

对于我的API服务器,我为Hapi编写了一个插件来处理这个问题。看一看,它可能对你有帮助。

'use strict';

var bluebird = require('bluebird');
var mongoose = bluebird.promisifyAll(require('mongoose'));

exports.register = function(plugin, options, next) {

  mongoose.connect(options.mongo.uri, options.mongo.options, function (e) {
    if (e) {
      plugin.log(['error', 'database', 'mongodb'], 'Unable to connect to MongoDB: ' + e.message);
      process.exit();
    }

    mongoose.connection.once('open', function () {
      plugin.log(['info', 'database', 'mongodb'], 'Connected to MongoDB @ ' +  options.mongo.uri);
    });

    mongoose.connection.on('connected', function () {
      plugin.log(['info', 'database', 'mongodb'], 'Connected to MongoDB @ ' +  options.mongo.uri);
    });

    mongoose.connection.on('error', function (e) {
      plugin.log(['error', 'database', 'mongodb'], 'MongoDB ' + e.message);
    });

    mongoose.connection.on('disconnected', function () {
      plugin.log(['warn', 'database', 'mongodb'], 'MongoDB was disconnected');
    });
  });

  return next();
};

exports.register.attributes = {
  name: 'mongoose',
  version: '1.0.0'
};