我是nodejs的新手,对我来说是如此的赤裸裸,我试图连接一些繁重的任务,比如游戏服务器,我有一个mysql轮询和一个函数create_game,它将使用轮询来获得新的连接
所以我注意到有时候nodejs会无缘无故地停止工作,我通过在每一行放上数字来追踪create_game函数中的问题,比如
console.log(` @-> ${debug_id} :1 `);
console.log(` @-> ${debug_id} : 2 `);查看哪一行破坏了我的代码
var pool = mysql.createPool({
connectionLimit : 20 ,
host : myEnv.parsed.DB_HOST,
user : myEnv.parsed.DB_USERNAME,
password : myEnv.parsed.DB_PASSWORD,
database : myEnv.parsed.DB_DATABASE
});
function create_game( debug_id ) {
console.log(` @-> ${debug_id} : 1 `);
let promise = new Promise(function(resolve , reject ) {
console.log(` @-> ${debug_id} : 2 `);
pool.getConnection(function(err, connection) {
console.log(` @-> ${debug_id} : 3 `);
if (err) {
console.log(` @-> ${debug_id} : 3E `);
reject(err.sqlMessage);
}
else
{
connection.beginTransaction(function (err) {
/// do stufff
console.log(` @-> ${debug_id} : success `);
});
}
});
})
.then(function (res) {
consoleLog('create success');
})
.catch(function (error) {
consoleLog('///////////ERROR///////////');
consoleLog(error);
});
}这是我在控制台中得到的
@-> 7 : 1
@-> 7 : 2
@-> 7 : 3
@-> 7 : 4
@-> 7 : 5
@-> 7 : 6
@-> 7 : 7
@-> 7 : 8
@-> 7 : 9
@-> 7 : 10
@-> 7 : 11
@-> 7 : 12
@-> 7 : success
@-> 8 : 1
@-> 8 : 2因此,根据输出结果,我认为pool.getConnection失败了,因为它在这一点上击中了connectionLimit : 20
那么我做错了什么呢?为什么代码会崩溃..我的意思是,我在这里有一个处理pool.getConnection失败的代码,那么为什么我得不到3和3E输出呢?
pool.getConnection(function(err, connection) {
console.log(` @-> ${debug_id} : 3 `);
if (err) {
console.log(` @-> ${debug_id} : 3E `);
reject(err.sqlMessage);
}我仍然看到终端中的套接字连接正在建立,因此节点脚本仍然有效…但是在此之后,所有与数据库相关的操作将停止工作,不会出现任何错误或输出
发布于 2020-10-29 22:31:31
您需要提供更多信息。您没有提到您使用的是什么mysql库吗?您显示的日志与代码不匹配。即logs 4-12在哪里
因此,我假设您使用的是mysqljs/mysql。
从您所展示的代码中可以观察到,当您从池中获取连接时,还需要释放它,这可能是问题的一个原因。您还没有显示您正在释放连接,所以我只能假设您没有。
pool.getConnection(function(err, connection) {
connection.query('SELECT * FROM sometable', function (error, results, fields) {
// When done with the connection, release it.
connection.release();
// Handle error after the release.
if (error) throw error;
// Don't use the connection here, it has been returned to the pool.
});
});请参阅https://github.com/mysqljs/mysql#pooling-connections
如果您不释放连接,您将用完池中的所有连接,并且连接的其他请求将被排队,并且将显示您所描述的行为。
另一方面,您还可以直接在池上查询,一旦查询完成,池将处理将连接释放回池的操作。这可能不适合上面的用例,因为看起来您正在使用连接作为事务的一部分-其中您确实需要对底层连接的引用。
发布于 2020-10-26 22:31:38
函数pool.getConnection()还需要一个分配池,如果此函数调用失败,则可能需要添加另一个错误处理程序。
https://stackoverflow.com/questions/64512151
复制相似问题