如何突破10个数据库连接池的连接限制?
问题分析与解决方案
Hey there, I can spot the issue right away—your code isn't releasing database connections back to the pool, which is why it gets stuck once all 10 connections are used up!
Let's break down what's happening:
- The
pool.connect()method gives you adonefunction specifically to return the client to the connection pool after you're done with it. - In your current code, you never call
done(), so each request holds onto its connection permanently. Once 10 requests have been processed, the pool has no free connections left to handle new requests.
Fixed Code
Here's how to adjust your API endpoint to properly release connections, even if an error occurs:
app.get('/test', function(req, resp) { pool.connect(function(err, client, done) { // First handle any connection errors if (err) { resp.status(500).json({ error: 'Failed to connect to database' }); return; } const query = client.query('SELECT * FROM mytable;', (err, res) => { // Always call done() to release the connection, no matter what done(); if (err) { resp.status(500).json({ error: err.message }); return; } resp.json(res.rows); }); }); });
Key Improvements:
- Added error handling for the initial connection attempt—if we can't get a client from the pool, we return an error instead of hanging.
- Called
done()inside the query callback, ensuring the connection is released whether the query succeeds or fails. This prevents connection leaks that drain your pool. - Added error handling for the query itself, so your API returns meaningful error responses instead of crashing.
Extra Tips
- You might also want to set a
connectionTimeoutMillisin your pool configuration—this ensures that if a connection is stuck, it gets cleaned up automatically after a set time. - Consider using async/await syntax for cleaner error handling (though the callback approach works fine once you fix the
done()call):app.get('/test', async function(req, resp) { let client; try { client = await pool.connect(); const res = await client.query('SELECT * FROM mytable;'); resp.json(res.rows); } catch (err) { resp.status(500).json({ error: err.message }); } finally { if (client) client.release(); // Equivalent to done() in callback style } });
内容的提问来源于stack exchange,提问作者Nuno Rolo
相关产品推荐
相关产品推荐

