每次查询数据库时都需要使用pg.connect()吗?在查看了githhub页面和wiki之后,示例显示了一个类似于这样的pg.connect回调内部的查询(注释来自github示例,我没有编写它们)
//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
});
});这些注释令人困惑,因为它听起来像是pg.connect()在使用每个调用创建一个新的客户机池,这显然是效率低下的。我在文档中看到了创建客户端的其他示例,但我希望使用客户机池。
发布于 2015-12-12 08:21:37
是的,pg.connect是推荐的做事方式。如github页面所述:https://github.com/brianc/node-postgres。它不是为每个请求创建一个池,而是一个新的请求将创建一个“池”,所有后续的查询都会添加到该连接中,直到超时30秒。//它将保持空闲连接打开30秒(可配置的),因此当应用程序未被使用时没有连接,但是一旦您每秒钟收到几个查询,它们都会在该连接上排队。可以更改超时时间和排队数量。
https://stackoverflow.com/questions/34236867
复制相似问题