【问题标题】:pg pool - whats right way to utilise pg pool with timeout functionalitypg pool - 使用具有超时功能的 pg pool 的正确方法是什么
【发布时间】:2018-01-25 14:54:45
【问题描述】:

我需要一些关于 pg npm 的帮助。

我已经阅读了许多文章和示例,并且对以正确的方式使用 pg 池感到完全困惑。我读过的很多文章都是旧的。

我想向您展示我的一些代码以及我是如何围绕 db 构建所有内容的。我几乎不担心需要您的支持。

这就是我的实现方式:

我只在服务器启动时与 Postgres 建立一次连接。

let pg = require('pg')

const db_config = {
    user : DB_USER,
    password : DB_PWD,
    database : DB_NAME,
    host : DB_HOST,
    max : 5, // max number of clients in the pool
    connectionTimeoutMillis : 5000,
    idleTimeoutMillis : 30000
};

conn = new pg.Pool(db_config);

conn.connect((err, client, done) => {
    if (err) {
        log.error(err.message);
        log.error(`could not connect to database`);
    } else {
        conn.query('SELECT 1', (err, res) => {
            done();
            if (err) {
                log.error(err)
            } else {
                log.info("connected to database");
            }
        });
    }
});

请注意conn 对象是全局的,我会在程序中的任何地方进一步使用它。

然后我启动我的 HTTP 服务器。到达服务器的每个请求平均必须运行大约 25 个数据库查询。在程序的生命周期中,我使用相同的 conn 对象来触发查询,如下所示。代码中的每个函数都只包含以下查询代码。

conn.query(query, function (err, docs) {    
    if (err) {
        log.error(err);
    } else {
        // do something 
    }
});

我正在使用“pg”:“^6.2.2”

——————————————————

我的担忧:

  1. 我在使用游泳池吗?

  2. 如何正确利用池?

  3. 每次在代码中执行任何查询之前,我是否需要连接到 pg,这意味着 conn.connect?

  4. 如果无法访问数据库,代码在读取时挂起然后很长时间后超时,我该如何处理?有什么方法可以让我在想要的时间之后超时?

【问题讨论】:

  • 最好不要使用它。相反,使用pg-promise,它隐藏了与连接使用相关的所有复杂性。

标签: node.js postgresql connection-timeout node-pg-pool


【解决方案1】:

我知道这是一个针对pg 6.2.2 的老问题,但我会为pg 7+ 回答这个问题(很容易更新),因为我也遇到了同样的问题并且束手无策。

以下是我如何使用您的代码将其设置为使用池。 pg 足够聪明,可以在立即或稍后再次使用 conn.connect() 时知道池已经存在。我将逻辑包装在一个可以轻松重用的查询函数中。现在出错时不会挂起,但出错时可能会返回意外数据,请注意。

let pg = require('pg')

const db_config = {
  user : DB_USER,
  password : DB_PWD,
  database : DB_NAME,
  host : DB_HOST,
  max : 5, // max number of clients in the pool
  connectionTimeoutMillis : 5000,
  idleTimeoutMillis : 30000
};

const conn = new pg.Pool(db_config);

function query(sql, cb) {
  conn.connect((err, client, done) => {
    if (err) {
      log.error(err.message);
      log.error(`could not connect to database`);
      cb(err);
      done();
    }
    else {
      client.query(sql, (err, res) => {
        cb(res);
        done();
        if (err) {
          log.error(err)
        }
        else {
          log.info("connected to database");
        }
      });
    }
  });
}

然后要运行查询,只需执行以下操作:

// run a query
query("SELECT 1", function(result) {
  console.log(result);
});

【讨论】:

    猜你喜欢
    • 2020-01-28
    • 2018-02-23
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    • 2023-02-15
    • 1970-01-01
    • 2016-12-27
    • 2019-08-13
    相关资源
    最近更新 更多