如何在pg模块中断开池

时间:2018-05-22 13:33:30

标签: node.js postgresql node-postgres node-pg-pool

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

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

connecting中,它只使用了一个新的游泳池,然后它显示我必须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()

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

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

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

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,没有从该连接返回的客户端,并且没有断开池的功能(只有结束它,最终再次以{ {1}})。

请就正确的池使用情况和语法提供建议

由于

1 个答案:

答案 0 :(得分:4)

我还遇到了另一个用于mssql的npm包。

经过一些跟踪和错误后,我决定选择一个处理连接的singelton(静态也可能)类。

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

这样的事情:

    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;