javascript – 什么是正确的方法使用node.js postgresql模块?

我在Heroku上编写一个node.js应用程序并使用pg module.我无法找出“正确”的方式来获取客户端对象的每个请求,我需要查询数据库。


pg.connect(conString, function(err, client) {
  // Use the client to do things here

但是你肯定不需要在每个使用数据库的函数中调用pg.connect?我看过other code这样做:

var conString = process.env.DATABASE_URL || "tcp://postgres:1234@localhost/postgres";
var client = new pg.Client(conString);
// client is a global so you can use it anywhere now


我是node-postgres的作者。首先,我道歉,文件没有做出正确的选择清楚:这是我的错。我会尽力改善它。我写了a Gist刚才解释这个,因为the conversation增长太长的Twitter。

Using pg.connect is the way to go in a web environment.

PostgreSQL server can only handle 1 query at a time per connection.
That means if you have 1 global new pg.Client() connected to your
backend your entire app is bottleknecked based on how fast postgres
can respond to queries. It literally will line everything up, queuing
each query. Yeah, it’s async and so that’s alright…but wouldn’t you
rather multiply your throughput by 10x? Use pg.connect set the
pg.defaults.poolSize to something sane (we do 25-100, not sure the
right number yet).

new pg.Client is for when you know what you’re doing. When you need
a single long lived client for some reason or need to very carefully
control the life-cycle. A good example of this is when using
LISTEN/NOTIFY. The listening client needs to be around and
connected and not shared so it can properly handle NOTIFY messages.
Other example would be when opening up a 1-off client to kill some
hung stuff or in command line scripts.


module.exports = {
   query: function(text, values, cb) {
      pg.connect(function(err, client, done) {
        client.query(text, values, function(err, result) {
          cb(err, result);


看看node-pg-query module做到这一点。

转载请明显位置注明出处:javascript – 什么是正确的方法使用node.js postgresql模块?