单独文件中的 NodeJS mysql2 连接即将停止

NodeJS mysql2 connection in separate file stops soon

connection.js

let mysql = require('mysql2');
let pool = mysql.createPool({
  host:'localhost',
  user: 'root',
  database: '',
  password: '',
  connectionTimeout: 10000
}).promise()

pool.getConnection(function(err, connection) {
  console.log('connected to database')
});

pool.on('error', function(err) {
  console.log(err.code);
});

module.exports = {
  getConnection: () => {
    return pool.getConnection()
  }
};

other_file.js

router.get('/', async (req, res) => {

    const conn = await connWrapper.getConnection();

    let [courses] = await conn.execute('SELECT * FROM courses');
    courses = courses;

    //database stuff here and page rendering etc

});

如果我第一次加载该页面,它可以工作,但是几秒钟后它停止工作并且该页面将不再加载,即使我删除了 connectionTimeout。 另外,我怎么没有收到来自 pool.getConnection 和 pool.on('error') 的日志。 控制台中没有任何日志。

您需要在不再需要后将连接释放回池中。默认池配置 ID connectionLimit: 10, queueLimit: 0,因此您的前 10 个请求使用池中的所有可用连接,之后的请求停留在 await connWrapper.getConnection(); 行等待以前的连接可用。

返回连接池的示例:

router.get('/', async (req, res) => {
  const conn = await connWrapper.getConnection();
  try { 
    const [courses] = await conn.execute('SELECT * FROM courses');
    //...
  } 
  finally {
    conn.release(); // no need to await here, .release() is sync call
  }  
});

或者您可以只在池上使用 .execute() 助手:

// add this to connection.js:
// execute: (...args) => pool.execute(...args)

router.get('/', async (req, res) => {
  const [courses] = await connWrapper.execute('SELECT * FROM courses');
  // ...
});