节点JS和pg模块“如何真正关闭连接?”

Jos*_*igo 0 javascript postgresql node.js

我对节点pg模块发疯了,收到“已经有太多客户端”错误。

app.js例如,我的文件管理着一些路由,在这些路由中我查询了一些数据到postgres。app.js看起来像下面这样:

//First I create a client
var client = new pg.Client(connectionString);
// Then I use that client to every routes, for example:
ContPg.prototype.someController = function(req, res){
    client.connect(function(error){
        if(error) return console.error('error conectando', error); 
        // Need to close client if there's an error connecting??

        client.query(someQuery, function(e,r){
            client.end(); 
            // Here sometimes I dont end client if i need to query more data 
            if(e) return console.error('error consultando', e);
            // Do anything with result...
        })
    });
}
Run Code Online (Sandbox Code Playgroud)

就像我说过的那样,我将该文件的所有路由都使用该客户端pg.js,但是在具有其他路由的其他文件中,我也这样做以连接到postgres(创建客户端并用于管理该文件的所有路由)

问题

我的代码有问题吗?我终止了错误的客户端连接?如果没有问题,是什么导致“已经有太多客户”错误?

提前致谢!!

jca*_*ron 5

推荐的模式是使用客户端池。从node-postgres文档中

通常,您将通过客户端池访问PostgreSQL服务器。客户端花费大量时间来建立新的连接。客户端也会在PostgreSQL服务器上消耗大量资源-不是您要对每个HTTP请求执行的操作。好消息:node-postgres附带内置的客户端池。

var pg = require('pg');
var conString = "postgres://username:password@localhost/database";

//this initializes a connection pool
//it will keep idle connections open for a (configurable) 30 seconds
//and set a limit of 20 (also configurable)
pg.connect(conString, function(err, client, done) {
  if(err) {
    return console.error('error fetching client from pool', err);
  }
  client.query('SELECT $1::int AS number', ['1'], function(err, result) {
    //call `done()` to release the client back to the pool
    done();

    if(err) {
      return console.error('error running query', err);
    }
    console.log(result.rows[0].number);
    //output: 1
  });
});
Run Code Online (Sandbox Code Playgroud)

别忘了打电话,done()否则您将有麻烦!

  • 对于需要访问 Postgresql 服务器的每个(Web)请求,您可以调用“pg.connect”来获取客户端,完成后,您可以调用“done”。 (2认同)