【发布时间】:2019-08-19 16:22:24
【问题描述】:
Postgres 和一般事务池概念的新手。在文档中,Postgres 建议对单个查询使用 pool.query 方法,并警告“You must always return the client to the pool if you successfully check it out”。我的意思是,您必须为客户端调用 client.release() 或为池调用 pool.end() (如果我错了,请纠正我)。所以在我的 Node/Express 服务器中,我做了一个简单的测试:
const { Pool } = require('pg');
const pool = new Pool();
...
router.post('/test', async (req, res) => {
let { username } = req.body;
let dbRes;
try{
dbRes = await pool.query('SELECT * FROM users WHERE username = $1', [username]);
} catch(err){
let errMsg = "Error fetching user data: " + err;
console.error(errMsg);
return res.send({"actionSuccess": false, "error": errMsg});
}
//do something with dbRes, maybe do an update query;
try{
await pool.end();
} catch(err){
return "There was an error ending database pool: " + err.stack;
}
res.send({"dbRes": dbRes.rows[0]})
});
我运行服务器,使用 Postman 对该/test 路由进行后调用,一切正常。但是,如果我再次拨打相同的电话,这次我会收到错误 Error: Cannot use a pool after calling end on the pool。这是有道理的,我在这个请求中结束了池,但同时它没有意义。我猜池/客户端没有像我最初想象的那样绑定到单个服务器请求,这意味着如果对节点服务器的一个请求结束了池,它也会结束所有其他请求的池(如果我错了,请纠正我!我只是在这里猜测)。如果是这种情况,那么我永远不能调用 pool.end(),因为只要节点服务器正在运行,我想保持 tje 池打开/活动,对于其他服务器请求也是如此。这就引出了一个问题,我应该在哪里结束游泳池?可以永远打开它吗?这是否与文档中所述的整个 You must always return the client to the pool if you successfully check it out 规则相冲突?
【问题讨论】:
标签: node.js postgresql express node-postgres