MongoDB连接池

mongodb的MongoClinet是已经内置连接池了的,可以通过poolSize修改配置,至于获取连接实例,只需要用nodejs维持一个单例就可以了:

var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/shop'

var option = {
    reconnectTries: 3,
    auto_reconnect: true,
    poolSize : 40,
    connectTimeoutMS: 500,
    useNewUrlParser: true
};

function MongoPool(){}

var p_db;

function initPool(cb){
  MongoClient.connect(url, option, function(err, db) {
    if (err) throw err;

    p_db = db;
    if(cb && typeof(cb) == 'function')
        cb(p_db);
  });
  return MongoPool;
}

MongoPool.initPool = initPool;

function getInstance(cb){
  if(!p_db){
    initPool(cb)
  }
  else{
    if(cb && typeof(cb) == 'function')
      cb(p_db);
  }
}
MongoPool.getInstance = getInstance;

module.exports = MongoPool;

调用时:

var MongoClient = require('mongodb').MongoClient
var app = require('express')()
var MongoPool = require('./db/dbPool.js')

app.listen(3000, function() {
  MongoPool.initPool()
  console.log('serve start successfully on the port: 3000')
})

app.get("/", function(req, res) {
  MongoPool.getInstance(function (client){
    var db = client.db('shop')
    db.collection('user').find({}).toArray(function(err, result) {
      res.end(JSON.stringify(result))
    })
  });
});

你可能感兴趣的:(MongoDB连接池)