我对节点 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...
})
});
}
正如我所说,我将该客户端用于文件pg.js
中的所有路由,但在具有其他路由的其他文件中,我也会这样做以连接到postgres(创建客户端并用于管理该文件的所有路由)
问题
我的代码有问题吗?我结束了错误的客户端连接?如果没有任何问题,什么可能导致"已经有太多客户端"错误?
提前感谢!!
建议的模式是使用客户端池。从node-postgres
文档中:
通常,您将通过 客户。客户需要花费大量时间来建立 新连接。客户端还消耗了大量 PostgreSQL 服务器上的资源 - 不是你想做的事情 每个 HTTP 请求。好消息:节点后方带有内置 客户端池。
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
});
});
别忘了打电话给done()
否则你会有麻烦的!