节点JS和pg模块'我怎么能真正关闭连接?' [英] Node JS and pg module 'How can I really close connection?'
问题描述
我对节点pg模块感到疯狂,已经有太多客户端错误。
I'm going crazy with node pg module, getting 'too many clients already' error.
我的 app.js $例如,c $ c>文件管理我查询一些数据到postgres的一些路由。
app.js
看起来如下:
My app.js
file for example, manages some routes in which I query some data to postgres. app.js
looks like bellow:
//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...
})
});
}
正如我所说,我将该客户端用于文件<$ c $中的所有路径c> pg.js ,但是在其他路由的其他文件中我也会这样做以连接到postgres(创建客户端并用于管理该文件的所有路由)
As I said I use that client for all routes in file pg.js
, but in other files with other routes I do the same to connect to postgres (create client and use for all routes that manage that file)
问题
我的代码有问题吗?我结束了错误的客户连接?
如果没有任何问题,可能导致已经有太多客户的错误?
Is something wrong with my code? I ended wrong client connection? If there's nothing wrong, what could be causing 'too many clients already' error?
提前致谢!!
推荐答案
推荐的模式是使用客户端池。来自 node-postgres
文档:
The recommended pattern is to use client pooling. From the node-postgres
documentation:
通常,您将通过
客户端池访问PostgreSQL服务器。客户端需要花费大量时间来建立
的新连接。客户端还在PostgreSQL服务器上消耗了大量的
资源 - 这不是你想要在
每个http请求上做的事情。好消息:node-postgres附带内置的
客户端池。
Generally you will access the PostgreSQL server through a pool of clients. A client takes a non-trivial amount of time to establish a new connection. A client also consumes a non-trivial amount of resources on the PostgreSQL server - not something you want to do on every http request. Good news: node-postgres ships with built in client pooling.
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()
或者你会遇到麻烦!
Don't forget to call done()
or you'll be in trouble!
这篇关于节点JS和pg模块'我怎么能真正关闭连接?'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!