何时断开连接以及何时结束 pg 客户端或池

2024-04-05

我的堆栈是node、express 和pg 模块。我真的尝试通过文档和一些过时的教程来理解。我不知道何时以及如何断开和结束客户端。

对于某些路线,我决定使用游泳池。这是我的代码

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

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

app.get('/', (req, res)=>{
  pool.connect()
    .then(client => {
      return client.query('select ....')
            .then(resolved => {
              client.release();
              console.log(resolved.rows);
            })
            .catch(e => { 
              client.release();
              console.log('error', e);
            })
      pool.end();
    })
});

在 CMS 的路由中,我使用客户端而不是具有与池不同的数据库权限的池。

const client = new pg.Client({
  user: 'clientuser',host: 'localhost',database: 'mydb',password: 'clientuser',port: 5432});    
client.connect();

const signup = (user) => {
  return new Promise((resolved, rejeted)=>{
    getUser(user.email)
    .then(getUserRes => {
      if (!getUserRes) {
        return resolved(false);
      }            
            client.query('insert into user(username, password) values ($1,$2)',[user.username,user.password])
              .then(queryRes => {
                client.end();
                resolved(true);
              })
              .catch(queryError => {
                client.end();
                rejeted('username already used');
              });
    })
    .catch(getUserError => {
      return rejeted('error');
    });
  }) 
};

const getUser = (username) => {
  return new Promise((resolved, rejeted)=>{
    client.query('select username from user WHERE username= $1',[username])
      .then(res => {
        client.end();
        if (res.rows.length == 0) {
          return resolved(true);
        }
        resolved(false);
      })
      .catch(e => {
        client.end();
        console.error('error ', e);
      });
  })
}

在这种情况下,如果我得到username already used并尝试使用另一个用户名重新发布,查询getUser永远不会启动并且页面挂起。如果我删除client.end();从这两个函数来看,它都会起作用。

我很困惑,所以请建议如何以及何时断开连接并完全结束池或客户端。任何提示、解释或教程将不胜感激。

谢谢


首先,从PG文档 https://node-postgres.com/features/pooling*:

const { Pool } = require('pg')

const pool = new Pool()

// the pool with emit an error on behalf of any idle clients
// it contains if a backend error or network partition happens
pool.on('error', (err, client) => {
  console.error('Unexpected error on idle client', err) // your callback here
  process.exit(-1)
})

// promise - checkout a client
pool.connect()
  .then(client => {
    return client.query('SELECT * FROM users WHERE id = $1', [1]) // your query string here
      .then(res => {
        client.release()
        console.log(res.rows[0]) // your callback here
      })
      .catch(e => {
        client.release()
        console.log(err.stack) // your callback here
      })
  })

这段代码/结构是足够的/made 让你的池正常工作,提供你的事在这里事物。如果您关闭应用程序,连接将正常挂起,因为池创建良好,完全不会挂起,即使它确实提供了手动挂起方式, 请参阅最后一节article https://node-postgres.com/features/pooling。 另请参阅前面的红色部分,其中显示“您必须始终返回客户端...”以接受

  • 强制性的client.release()操作说明
  • 在访问参数之前。
  • 您的回调范围/关闭客户端。

Then, 来自pg.client 文档 https://node-postgres.com/api/client*:

带有承诺的纯文本查询

const { Client } = require('pg').Client
const client = new Client()
client.connect()
client.query('SELECT NOW()') // your query string here
  .then(result => console.log(result)) // your callback here
  .catch(e => console.error(e.stack)) // your callback here
  .then(() => client.end())

在我看来最清晰的语法:

  • 不管结果如何,你都会结束客户。
  • 您之前访问过结果ending客户端。
  • 您不会在回调中范围/关闭客户端

两种语法之间的这种对立乍一看可能会令人困惑,但其中并没有什么神奇之处,它是实现构造语法。 专注于your回调和查询,而不是这些构造,只需选择最适合您的眼睛并用你的喂它 code.

*我添加了评论// 这里是你的xxx为了清楚起见

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

何时断开连接以及何时结束 pg 客户端或池 的相关文章

随机推荐