[英]How to handle a full pool of mysql connections in nodejs
In my Node script I use MySQL and to be able to handle multiple connections I use a connection pool.在我的节点脚本中,我使用 MySQL 并且能够处理多个连接,我使用连接池。
Today I forgot to release a connection in the mysql pool.今天忘记在 mysql 池中释放一个连接。 It took me a long time to figure out what the problem was because there was no error shown anywhere.
我花了很长时间才弄清楚问题是什么,因为任何地方都没有显示错误。
My code:我的代码:
const mysql = require('mysql');
const pool = mysql.createPool({
host : 'x',
user : 'x',
password : '#x',
database : 'x',
connectionLimit: 2
});
function executeQuery(){
pool.getConnection((err, connection) => {
if(err) console.log(err);
let query = mysql.format("SELECT * FROM users WHERE id = ?", 1);
connection.query(query, (err, rows) => {
if(err) console.log(err);
console.log(rows);
});
});
}
executeQuery(); // outputs the user as expected
executeQuery(); // outputs the user as expected
executeQuery(); // there is no output in the console, it just looks like nothing happened
My question: How to find out if there are still connections available and if there are no connection available anymore show an error or handle it in a different way?我的问题:如何确定是否仍有可用的连接,如果没有可用的连接不再显示错误或以不同的方式处理它?
You forgot to release
your connection:您忘记
release
连接:
function executeQuery(){
pool.getConnection((err, connection) => {
if(err) console.log(err);
connection.query("SELECT * FROM users WHERE id = ?", [ 1 ], (err, rows) => {
connection.release(); // Give it back or else it gets lost
if(err) console.log(err);
console.log(rows);
});
});
}
There's also no reason to grab the connection like that, you can just use the pool:也没有理由像那样抓住连接,您可以使用池:
function executeQuery() {
pool.query("SELECT * FROM users WHERE id = ?", [ 1 ], (err, connection) => {
if(err) console.log(err);
console.log(rows);
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.