如何在服务器中使用node-postgres?
我在写一个使用Postgres数据库的Node.js Web服务器。 我曾经连接每个新的请求,像这样:
app.get('/', function (req, res) { pg.connect(pgconnstring, function (err, client) { // ... }); });
但是经过几次请求,我发现在尝试连接时Heroku上出现“内存不足”的错误。 我的数据库只有10行,所以我不明白这是如何发生的。 我所有的数据库访问都是这种forms:
client.query('SELECT * FROM table', function (err, result) { if (err) { res.send(500, 'database error'); return; } res.set('Content-Type', 'application/json'); res.send(JSON.stringify({ data: result.rows.map(makeJSON) })); });
假设内存错误是由于有几个持久连接到数据库,我切换到我在几个node-postgres
例子中看到的样式,只是在文件的顶部连接一次:
var client = new pg.Client(pgconnstring); client.connect(); app.get('/', function (req, res) { // ... });
但是现在我的请求挂起(无限期?),当我尝试执行查询连接中断后。 (我通过杀死一个Postgres服务器并将它重新启动来模拟它。)
那么我怎么做其中的一个呢?
- 适当地集中Postgres连接,以便每次都可以“重新连接”而不会耗尽内存。
- 让全局客户端在networking故障后自动重新连接。
我假设你正在使用最新版本的node-postgres,其中连接池已经大大改善。 你现在必须检查连接回池,否则你会stream血的连接:
app.get('/', function (req, res) { pg.connect(pgconnstring, function (err, client, done) { // do some stuff done(); }); });
至于在全局连接上的error handling(#2,但我会使用池):
client.on('error', function(e){ client.connect(); // would check the error, etc in a production app });
所有这些“缺失”文档都在GitHub wiki上 。