【问题标题】:NodeJS mysql2 connection in separate file stops soon单独文件中的NodeJS mysql2连接很快停止
【发布时间】:2020-07-28 17:23:00
【问题描述】:

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') 的日志。 控制台中没有任何日志。

【问题讨论】:

    标签: node.js express connection


    【解决方案1】:

    您需要在不再需要连接后将连接释放回池。默认池配置 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');
      // ...
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-25
      • 2019-11-17
      • 2021-06-08
      • 1970-01-01
      • 1970-01-01
      • 2013-03-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多