Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Node.js 使用 MySQL 連線池避免連線中斷

問題背景

在 Express 應用中直接使用 mysql 模組時,若站點閒置過久,資料庫連線可能逾時,導致 Node 進程出現連線錯誤。改用連線池可改善此問題。

建立連線池

使用 mysql.createPool 設定 host、user、password、database 與 port。查詢時透過 pool.getConnection 取得連線,用完後呼叫 connection.release 歸還。

程式範例

var pool = mysql.createPool({
  host: conf.dbMysql.host,
  user: conf.dbMysql.user,
  password: conf.dbMysql.password,
  database: conf.dbMysql.database,
  port: conf.dbMysql.port
});

router.get('/', function(req, res) {
  var sql = "select * from siteinfo order by id";
  pool.getConnection(function(err, connection) {
    if (err) throw err;
    connection.query(sql, function(err, rows) {
      if (err) throw err;
      res.render('sites', { title: '站點分布', results: rows });
    });
    connection.release();
  });
});

注意事項

release 必須在查詢完成後呼叫,避免連線被提前回收。若使用 async/await,也應確保每個請求都能正確釋放連線,防止連線池耗盡。

Copyright © Linux教程網 All Rights Reserved