2014-08-28 2 views
1

mongo에 대한 연결이 이미 있는지 확인하고 연결을 반환하는 mongo 연결 풀 팩터 리를 만들려고합니다. 연결 풀을 만들고 연결을 반환하지 않는 경우내 모듈을 필요로하는 여러 파일이 변수를 덮어 쓰는 중임

나는 이것을 mongo를 쿼리 할 여러 파일에서 필요로하고 싶다.

var fooMongoFactory = require('../../lib/mongoFactory').init(mongodb://localhost:27017/foo); 

을하고이 같은 파일에서 사용 : 각 파일은 다음과 몽고를 필요로한다

fooMongoFactory.getConnection().then(function(db) { 
    // do stuff 
}); 

제가하는 데 문제는 내가 다른 여러 지정할 수 있도록하려는 것입니다 mongo 인스턴스를 파일에 저장하지만, 그렇게 할 때 두 번째 init은 첫 번째 init보다 우선합니다. 예 :

var fooMongoFactory = require('../../lib/mongoFactory').init(mongodb://localhost:27017/foo); 
var barMongoFactory = require('../../lib/mongoFactory').init(mongodb://localhost:27017/bar); 

fooMongoFactory.getConnection().then(function(db) { 
    // querying in here is actually pointing at the mongo db "bar" 
}); 

내가 때마다 인스턴스화 할 필요없이 사용뿐만 아니라, 몽고의 여러 다른 인스턴스에 여러 파일이 같은 공장을 연결할 수 있도록 어떻게 내 공장을 조정할 수 있습니까? 나는 생성자를 사용하는 것을 생각했지만 mongoFactory를 사용하는 모든 단일 파일에 새로운 연결 풀을 생성합니다.

/** 
* Creates and manages the Mongo connection pool 
* 
* @type {exports} 
*/ 
var Q = require('q'); 
var MongoClient = require('mongodb').MongoClient; 
var dbPromise = null; 
var db = null; 

module.exports = function() { 

    return { 

    init: function init(connectionString) { 
     db = connectionString; 
     return module.exports; 
    }, 

    /** 
    * Gets a connection to Mongo from the pool. If the pool has not been instantiated it, 
    * instantiates it and returns a connection. Else it just returns a connection from the pool 
    * 
    * @returns {*} - A promise object that will resolve to a mongo db object 
    */ 
    getConnection: function getConnection() { 
     // get a connection to mongo using the db string and return dbPromise 
    } 
    } 
}(); 
+1

은/방법 'init'라고? –

+0

mongoFactory가 필요하면 Init가 호출됩니다. Init는 호출 스크립트가'getConnection'을 호출 할 때 사용할 db 변수를 설정합니다. 'getConnection'은 이전에 설정 한'db' 변수를 사용합니다. – Catfish

+0

"factory"라는 이름을 지정해도 공장이되지는 않습니다. http://en.wikipedia.org/wiki/Factory_method_pattern –

답변

0

연결하려는 mongodb의 연결 문자열을 전달해야하므로 모듈을 만들었습니다. 이 모듈은 궁극적으로 mongo에 대한 모든 연결을 추적하고 mongodb에 대한 현재 연결이 있는지 여부를 추적합니다.

/** 
* Creates and manages the Mongo connection pool 
* 
* @type {exports} 
*/ 
var Q = require('q'); 
var MongoClient = require('mongodb').MongoClient; 
var _ = require('underscore'); 

var connections = []; 
var dbPromise = null; 

module.exports = function() { 

    return { 

    /** 
    * Gets a connection to Mongo from the pool. If the pool has not been instantiated it, 
    * instantiates it and returns a connection. Else it just returns a connection from the pool 
    * 
    * @returns {*} - A promise object that will resolve to a mongo db object 
    */ 
    getConnection: function getConnection(connectionString) { 

     var def = Q.defer(); 

      // If connectionString is null or undefined, return an error 
      if(_.isEmpty(connectionString)) { 
       def.reject('getConnection must contain a first parameter'); 
       return dbPromise = def.promise; 
      } 

     // Check if connections contains an object with connectionString equal to the connectionString passed in and set the var to it 
     var pool = _.findWhere(connections, {connectionString: connectionString}); 

     // If no conneciton pool has been instantiated, instantiate it, else return a connection from the pool 
     if(_.isUndefined(pool)) { 

     // Initialize connection once 
     MongoClient.connect(connectionString, function(err, database) { 
      if (err) { 
      def.reject(err); 
      } 

      // Add the connection to the array 
      connections.push({connectionString: connectionString, db: database}); 

      def.resolve(database); 
     }); 

     } else { // Else we have not instantiated the pool yet and we need to 
     def.resolve(pool.db); 
     } 

     return dbPromise = def.promise; 
    } 
    }; 
}(); 

https://github.com/toymachiner62/mongo-factory

1

mongodb 노드 모듈은 이미 connect()를 호출 할 때 자동으로 사용됩니다 built-in connection pooling 기능이 있습니다. default max connection pool size is 5이지만 연결 URL에서이 값을 변경할 수 있습니다 (예 : 'mongodb://localhost:27017/foo?maxPoolSize=15').

server config optionspoolSizemaxPoolSize보다 작거나 같게 설정하여 생성 된 실제 연결 수를 변경하려는 경우도 있습니다. auto_reconnect을 true로 설정할 수도 있습니다.

이제는 해당 서버의 데이터베이스 개체를 포함하는 host : port에 개체를 키로 유지하십시오. 누군가가 당신의 객체의 host : port를 포함하는 연결 문자열을 전달한 다음 풀을 반환하십시오. 그렇지 않으면 새 데이터베이스 객체를 만들고 캐시하고 반환합니다.

+0

연결 풀링 기능이 내장되어 있지만 두 개의 파일이 각각 'connect()'라고하면 두 개의 연결이 생성됩니다. 이 mongoFactory를 작성하여이를 피하려고합니다. 유스 케이스에 내 hapijs 백엔드에 대한 여러 웹 서비스 호출을하는 웹 페이지가 있습니다. 만약 각각의 웹 서비스 호출이'connect()'를 호출하는 다른 파일을 호출한다면, 현재 다중 연결 풀을 열어 놓았습니다. – Catfish

관련 문제