4

所以,我在节点 8.11.1 / express 4.16.3 / pg 7.4.2 中使用pg 模块

我尝试将池用于我的前端(只是选择),示例有些令人困惑。

连接时它只使用一个新池,然后它表明我必须做pool.end()

const pool = new Pool({
  user: 'dbuser',
  host: 'database.server.com',
  database: 'mydb',
  password: 'secretpassword',
  port: 3211,
})

pool.query('SELECT NOW()', (err, res) => {
  console.log(err, res)
  pool.end()
})

我这样写了我的代码,Error: Cannot use a pool after calling end on the pool如果我做了几次相同的查询,它就会打印出来。所以不行pool.end()

查询中,示例中没有断开连接 (?)

我终于让我的代码像pooling一样。它显示了pool.on('error', (err, client) => {函数,然后client.release()在池中使用,因为“pool.query 在内部直接委托给 client.query”我猜?

那么,在 pg 中使用 pool 的正确方法是什么,以及如何在每次查询或失败后断开连接?我想出了这个

const pool = new pg.Pool({
  user: 'user',
  host: 'localhost',
  database: 'myProject',
  password: 'secret',
  port: 5432
});

pool.on('error', (err, client) => {
  console.error('error on client', err, 'on client' , client);
  process.exit(-1);
});

app.get('/', (req, res)=>{
  pool.connect()
    .then(client => {
      return client.query('select name from table')
           .then(resolved => {
              client.release();
              res.render('index',{'testData': resolved.rows});
            })
            .catch(e => { //return client.query
              client.release();
              res.render('index',{'errorData': e});
            })
      .catch(e => { //pool.connect()
        client.release();
        res.render('index',{'errorData': e});
      })
    })
});

我不知道这是否可以以任何方式缩短。比如,如果catch(e => { ////pool.connect()...需要或者它被覆盖pool.on('error', (err, client) => {...

此外,如果它像

const pool = new pg.Pool({
  user: 'user',
  host: 'localhost',
  database: 'myProject',
  password: 'secret',
  port: 5432
});
app.get('/', (req, res)=>{
  pool.query('...')
  .then(resolved => {          
      pool.end();// pool disconnect ???
      res.render('index',{
        'testData': resolved.rows
      });
  })
  .catch(e => {
      pool.end();// pool disconnect ???
      res.render('index',{
        'testData': e
      });
  })
});

但我不知道这是否正确,因为没有pool.connect,没有从该连接返回的客户端,也没有断开池的功能(只是为了结束它,再次以 结束Error: Cannot use a pool after calling end on the pool)。

请就正确的池使用和语法提出建议

谢谢

4

1 回答 1

4

我在使用另一个用于 mssql 的 npm 包时也遇到了这种问题。

经过一些尝试和错误后,我决定选择一个处理连接的单例(静态也可以)类。

现在,您只需在每次查询之前调用一个函数即可创建新的连接池或接收当前的连接池。

像这样的东西:

    let _this = {};
    let connectionPool = null;

    function getConnection(){
        if(connectionPool){
            return connectionPool
        } else { 
            connectionPool = new pg.Pool({
                user: 'user',
                host: 'localhost',
                database: 'myProject',
                password: 'secret',
                port: 5432
            });
            return connectionPool;
        }
    }

   function closeConnection(){
       // close connection here       
   }

    _this.getConnection = getConnection;
    _this.closeConnection = closeConnection;

   module.exports = _this;
于 2018-05-22T13:59:48.753 回答