Best practices of db connection pool handling in a node js app?

时间:2015-11-12 11:54:49

标签: node.js postgresql asynchronous

I'm referring to node-postgres package below, but I guess this question is rather generic.

There is this trivial example where you 1) acquire (connect) a connection (client) from the pool in the top level http request handler, 2) do all business inside of that handler and 3) release it back to the pool after you're done.

I guess it works fine for that example, but as soon as your app becomes somewhat bigger this becomes painfull soon.

I'm thinking of these two options, but I'm not quite sure...

  1. do the "get client + work + release client" approach everywhere I need to talk to db.

    This seems like a good choice, but will it not lead to eating up more than one connection/client per the top http request (there are parallel async db calls in many places in my project)?

  2. try to assign a globaly shared reference to one client/connection accessible via require()

    Is this a good idea and actually reasonably doable? Is it possible to nicely handle the "back to the pool release" in all ugly cases (errors in parallel async stuff for example)?

Thank you.

3 个答案:

答案 0 :(得分:1)

好吧,我失去了一些时间试图解决这个问题。最后,在经过一些考虑并受John Papa's code影响之后,我决定使用这样的database模块:

var Q = require('q');
var MongoClient = require('mongodb').MongoClient;

module.exports.getDb = getDb;

var db = null;

function getDb() {
  return Q.promise(theDb);

  function theDb(resolve, reject, notify) {
    if (db) {
      resolve(db);
    } else {
      MongoClient.connect(mongourl, mongoOptions, function(err, theDb) {            
          resolve(db);
        }
      });
    }
  }
}

所以,当我需要执行查询时:

getDb().then(function(db) {

    //performe query here

});

至少对于Mongodb来说,这是一种很好的做法,如here所示。

答案 1 :(得分:0)

最好的建议取决于数据库的类型和代表数据库的基本框架。

对于Postgres,基本框架/驱动程序是node-postgres,它嵌入了对连接池的支持。然而,这种支持是低水平的。

对于高级访问权限,请参阅pg-promise,其中提供了自动连接管理,支持taskstransactions等等。

答案 2 :(得分:0)

这对我来说效果很好。

var pg = require('pg');
var config = { pg : 'postgres://localhost/postgres' };

pg.connect(config.pg, function(err, client, done) {
  client.query('SELECT version();', function (err, results) {
    done();

    //do something with results.rows
  });
});