Promise-MySQL无法将连接释放回池 [英] Promise-MySQL cannot release connections back to the pool
问题描述
我对Node.js开发非常陌生,我正在开发一个需要我从mysql数据库中拉用户的应用程序.我正在使用promise-mysql
库查询mysql数据库.我正在尝试使用这样的连接池:
I am very new to Node.js development and I am working on an app that requires me to pull users from a mysql database. I am using the promise-mysql
library to query a mysql database. I am trying to use a connection pool like this:
var pool = mysql.createPool({
host: hgh.host,
user: hgh.user,
password: hgh.pw,
database: hgh.name,
connectionLimit: 10
});
作为模块中的全局变量.
As a global variable in my module.
然后我具有以上功能,可以从池中返回连接.
I then have the above function to return a connection from the pool.
function connect() {
return pool.getConnection().then(function(connection) {
return connection
}).catch(function(error) {
console.log("Connect failed");
throw ErrorModel.generateErrorObject(error, 500);
});
}
下面是我用来查询数据库的函数:
Below is a function I am using to query the database with:
function getUser(username) {
var sql_query = `SELECT * FROM userstable WHERE userName = ` + `'` + username + `'`;
return connect().then(function(conn) {
return conn.query(sql_query).then(function(rows) {
console.log("HGH getUser Then");
console.log(pool);
conn.release();
return rows;
});
}).catch(function(error) {
console.log("HGH getUser Catch");
console.log(error);
throw ErrorModel.generateErrorObject(error, 500);
});
}
我遇到了这个问题:
conn.release
在尝试将我当前的连接释放到池中时不起作用.我的逻辑在这里错了吗?我的目标是建立一个带有一堆连接的池(最多一定数量),如果用户需要查询,getConnection()
函数只是从池中获取它们的免费连接,或者创建一个连接.问题是我无法终生将其作为free
释放回池中.每次我使用conn.end()
而不是release
发出请求时,连接都保留在池的_allConnections
数组中对其进行控制,并且_freeConnections
数组中绝对没有连接.
conn.release
is not a function when trying to release my current connection into the pool. Is my logic wrong here? My goal is to have a pool with a bunch of connections (up to a certain number) and if a user needs to query, the getConnection()
function just grabs them either a free connection from the pool, or creates them one. Problem is I cannot for the life of me release it back to the pool as free
..Every time I make a request with conn.end()
instead of release
the connection remains in the _allConnections
array of the pool when I console it out, and there are absolutely no connections in the _freeConnections
array.
任何人都知道如何使连接再次免费?
Anyone know how I can make connections free again??
推荐答案
通过查看模块代码,我发现了从池中释放连接的功能:
Looking at the module's code I found the function for releasing a connection from a pool:
pool.prototype.releaseConnection = function releaseConnection(connection) {
//Use the underlying connection from the mysql-module here:
return this.pool.releaseConnection(connection.connection);
};
因此,如果所有这些功能都位于同一个文件中,则可以在getUser函数中执行以下操作: 替换
So if all of these functions live in the same file you could do the following in the getUser function: replace
conn.release();
使用
pool.releaseConnection(conn);
这篇关于Promise-MySQL无法将连接释放回池的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!