使用 pg-promise 的连接

Connections using pg-promise

所以我正在使用 pg-promise 来查询我的数据库。由于我使用的是 heroku postgres(免费版),最大连接数为 20。

要连接到数据库,我使用

pgp(process.env.DATABASE_URL + '?poolSize=10')
  .connect()
  .then( sco => {
    dbclient = sco;
  })
  .catch( err => {
    console.error(err);
  })

我正在使用 dbclient 变量来 运行 查询,例如

dbclient
  .one('select ...')
  .then(() => ...)
  .catch( res.status(500).send);

尽管我将池大小设置为 10,但连接数会无限增加并且我的应用程序会崩溃。

我该如何解决这个问题?我是否必须在每次 运行 查询时释放客户端?

编辑:

所以我编辑了我的代码,这正是我现在使用它的方式,但我仍然遇到同样的问题。

const pgp = require('pg-promise')();
pgp.pg.defaults.poolSize = 10;

router.get('/', (req, res) => {
  pgp(process.env.DATABASE_URL).any('select ...')
        .then((result) => res.status(200).send(result))
        .catch(err => res.status(500).send({err}));
});

首先,不要使用方法connect at all. The database object can manage connections automatically. Method connect is there only for some very specific tasks, like setting up listeners, or to

您应该直接针对 db 对象执行单个查询,并且您应该在 tasks or transactions. See also Chaining Queries.

中执行查询链

您可以通过连接参数更改默认池大小,使用 max,如下所示:{max: 20}。见 Connection Syntax.