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.connect();
// client is a global so you can use it anywhere now

我倾向于第二个选项,因为我相信Heroku的自由数据库实例被限制在一个连接,但是有这样做有任何缺点吗?我需要检查我的客户端对象是否仍然连接每次我使用它之前?

我是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.

一个非常有用的事情是将对应用程序中的数据库的所有访问集中到一个文件。不要垃圾pg.connect电话或新客户端。有一个像db.js这样的文件看起来像这样:

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

这样,你可以将你的实现从pg.connect更改为客户端的自定义池或任何,只需要在一个地方更改的东西。

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

http://stackoverflow.com/questions/8484404/what-is-the-proper-way-to-use-the-node-js-postgresql-module

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:javascript – 什么是正确的方法使用node.js postgresql模块?