【问题标题】:Postgres connection pooling error troubleshootingPostgres 连接池错误排查
【发布时间】:2019-11-16 20:53:13
【问题描述】:

我有一个用 nodejs 编写的 AWS Lambda 函数,它正在执行一组递归 postgres 数据库调用,每次第 81 次调用都会导致以下错误:

剩余的连接槽保留给非复制超级用户 连接

我假设我在 postgres 级别泄漏了一些东西,但我相信我坚持执行https://node-postgres.com/features/pooling 中定义的单个池查询的建议调用。我已经简化了我的代码,如下所示,这样我每次只执行相同的查询,结果仍然相同。函数 testHarness 是启动我的 Lamba 函数中的逻辑的原因。这里的意图是对 postgres 执行查询,一旦完成再次触发查询,本示例重复 500 次。当第 81 个调用发生时,它总是失败。 DB_CONNECT 环境变量包含连接信息,其中“MAX”值为 3。

function testHarness(cb){
    _test(0, cb);
}

function _test(pos, cb){
    console.log(pos);
    _testData(function (err, data){
        if (err) return cb(err);
        if (pos < 500){
            _test(pos + 1, cb);
        }
        else{
            return cb(null, 'done');
        }
    });
}
function _testData(cb){
    const { Pool } = require('pg')
    const pool = new Pool(JSON.parse(process.env.DB_CONNECT));
    const sql = 'SELECT id, url, pub_date, description, title, duration FROM episodes WHERE feed_id = $1 ORDER BY pub_date DESC LIMIT 10';

    pool.query(sql, ['28c65c8d-f96a-4499-a854-187eed7050bd'], (err, result) => {
        if (err) throw err;
        return cb(err, result);
    })
}

【问题讨论】:

  • 您应该全局创建pool 实例,而不是每次调用_testData

标签: node.js postgresql aws-lambda


【解决方案1】:

所以问题在于泄漏您在 _testData 函数中创建的 Pool 对象。使用Pool 后,您必须将其关闭并在“关闭”标题下找到文档here,如它所说:

  pool.end()

但是,您使用Pool 的方式没有意义。最好把它放在_testHarness函数中,以便能够重用连接并节省连接开销时间,让您的代码运行得更快:

function testHarness(cb){
    const { Pool } = require('pg')
    const pool = new Pool(JSON.parse(process.env.DB_CONNECT));

    _test(pool, 0, function(err, data){
      pool.end();
      cb(err, data);
    });
}

function _test(pool, pos, cb){
    console.log(pos);
    _testData(pool, function (err, data){
        if (err) return cb(err);
        if (pos < 500){
            _test(pos + 1, cb);
        }
        else{
            return cb(null, 'done');
        }
    });
}
function _testData(pool, cb){
    const sql = 'SELECT id, url, pub_date, description, title, duration FROM episodes WHERE feed_id = $1 ORDER BY pub_date DESC LIMIT 10';

    pool.query(sql, ['28c65c8d-f96a-4499-a854-187eed7050bd'], (err, result) => {
        if (err) throw err;
        return cb(err, result);
    })
}

我不是 AWS 用户,但我想它应该像任何其他 postgres 数据库服务一样,您可能需要对其进行一些更改以适应 AWS 服务。

另外,你没有能力使用async/await 模式吗?更容易理解。

【讨论】:

    猜你喜欢
    • 2018-11-26
    • 2021-10-05
    • 2017-10-31
    • 1970-01-01
    • 2012-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-11
    相关资源
    最近更新 更多