安全地保持 MySQL 连接处于活动状态

问题描述 投票:0回答:2

我正在开发一个连接到 MySQL 服务器的 Node.js 应用程序。不过,以下内容可能不是特定于 Node.js 的。

目前,我的代码在应用程序启动时初始化一个 MySQL 连接,然后每次需要进行查询时都使用该连接。

我的方法面临的问题是连接在一段时间后往往会关闭。我不知道那段时间有多长,但看起来至少有几个小时。我也不确定是否是不活动造成的。

无论如何,我想知道什么是长期管理 MySQL 连接的更好方法。在可能的方法中,我考虑过:

  • 只需在每次查询之前检查连接是否仍然有效。如果没有,请在执行查询之前重新连接。

  • 池化 MySQL 连接。对于一个相当小的应用程序来说,这会不会太过分了?

  • 定期(大约每小时)执行一次查询,以防由于不活动而发生这种情况。但是,这并不能解决并非由不活动引起的可能情况下的情况。

  • 在查询之前/之后连接和断开连接。坏主意,因为涉及到开销。

正如您可能想象的那样,我倾向于使用前两个选项之一。哪个选项最可靠、最有效?

mysql connection-timeout
2个回答
7
投票

Node.js 的最佳实践似乎是使用连接池。请参阅Node.js MySQL 需要持久连接

空闲连接的默认超时为 28800 秒,可以使用

wait_timeout
变量进行配置。请参阅 http://dev.mysql.com/doc/refman/5.6/en/server-system-variables.html#sysvar_wait_timeout


0
投票
/*----------
  @brief
In this code, const connectionsToPing = Math.floor(pool._freeConnections.length / 2) calculates the number of connections to ping as half of the available free connections.

By distributing the pings in this way, subsequent intervals will ping the remaining connections in the second half of _freeConnections , achieving a balanced distribution of keepalive pings over time.

This modification ensures that only a portion of the free connections are used for keepalive pings, preventing the exhaustion of all available connections in a single interval.
*/

const mysql = require("mysql");

// Create a MySQL connection pool
const pool = mysql.createPool({
  host: "localhost",
  user: "root",
  password: "password",
  database: "your_database",
  connectionLimit: 10 // Adjust the connection limit as per your need
});

// Function to send keepalives to a portion of connections in the pool
function sendKeepalives() {
  if (pool._freeConnections.length === 0) {
    console.log("No free connections available to send keepalives.");
    return;
  }//if

  const connectionsToPing = Math.floor(pool._freeConnections.length / 2);

  for (let i = 0; i < connectionsToPing; i++) {
    pool.getConnection((err, connection) => {
      if (err) {
        console.error("Error getting connection from pool:", err);
        return;
      }

      connection.ping(err => {
        connection.release();
        if (err) {
          console.error("Error sending keepalive:", err);
        } else {
          console.log("Keepalive sent successfully");
        }
      });
    });
  }//for
}//fn

// Schedule keepalives every 30 seconds
setInterval(sendKeepalives, 30000);

// You can now use the pool to execute queries or tasks
pool.query("SELECT * FROM your_table", (err, results) => {
  if (err) {
    console.error("Error executing query:", err);
    return;
  }
  console.log(results);
});

//end
© www.soinside.com 2019 - 2024. All rights reserved.