我有一个用 nodejs 编写的 AWS Lambda 函数,它正在执行一组递归的 postgres 数据库调用,每次在第 81 次调用时都会导致以下错误:
remaining connection slots are reserved for non-replication superuser connections
我假设我在 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);
})
}
最佳答案
所以问题是泄漏了您在 _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
模式吗?它更容易理解。
关于node.js - Postgres 连接池错误排查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58890547/