Mysql2 失去连接时出错,无法重新连接

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

我在nodejs(expressjs)中使用mysql2进行开发。当我关闭或重新启动 mysql 服务器时,我的应用程序会出现错误,nodemon 崩溃并且不会重新连接到 mysql 服务器。我想每 5 分钟重新连接一次。

这是我的代码:

const mysql = require('mysql2');

let db;

const dbConfig = {
  host: HOST_DB,
  user: USER_DB,
  password: PASSWORD_DB,
  database: DATABASE_NAME,
  port: PORT_DB,
};

function handleDisconnect() {

  db = mysql.createConnection(dbConfig);

  db.connect(error => {
    if (error) {
      console.error('Error connecting to the database:', error);
      setTimeout(handleDisconnect, 300000);
    }
  });

  db.on('error', error => {
    console.error('Database error:', error);
    if (error.code === 'PROTOCOL_CONNECTION_LOST') {
      console.log('Attempting to reconnect to the database...');
      handleDisconnect();
    } else {
      throw error;
    }
  });

}
handleDisconnect()

db = mysql.createConnection(dbConfig);

错误:

node:events:497
      throw er; // Unhandled 'error' event
      ^

Error: Connection lost: The server closed the connection.
    at Socket.<anonymous> (C:\Users\admin\Desktop\otp\server\node_modules\mysql2\lib\connection.js:117:31)
    at Socket.emit (node:events:519:28)
    at TCP.<anonymous> (node:net:338:12)
Emitted 'error' event on Connection instance at:
    at Connection._notifyError (C:\Users\admin\Desktop\otp\server\node_modules\mysql2\lib\connection.js:252:12)
    at Socket.<anonymous> (C:\Users\admin\Desktop\otp\server\node_modules\mysql2\lib\connection.js:123:12)
    at Socket.emit (node:events:519:28)
    at TCP.<anonymous> (node:net:338:12) {
  fatal: true,
  code: 'PROTOCOL_CONNECTION_LOST'
}

Node.js v20.15.0
[nodemon] app crashed - waiting for file changes before starting...

我想每 5 分钟重新连接一次 mysql 服务器。然后我的后端服务器就可以工作,而无需我关闭它并重新启动它。

javascript node.js express mysql-connector mysql2
1个回答
0
投票

您可以结合使用连接池和重新连接机制

const mysql = require('mysql2');
const dbConfig = {
  host: HOST_DB,
  user: USER_DB,
  password: PASSWORD_DB,
  database: DATABASE_NAME,
  port: PORT_DB,
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0
};

let pool;

function createPool() {
  pool = mysql.createPool(dbConfig);

  pool.on('connection', function (connection) {
    console.log('Database connection established');
  });

  pool.on('error', function (err) {
    console.error('Database error:', err);
    if (err.code === 'PROTOCOL_CONNECTION_LOST' || err.code === 'ECONNREFUSED' || err.code === 'ER_ACCESS_DENIED_ERROR') {
      console.log('Attempting to reconnect to the database in 5 minutes...');
      setTimeout(createPool, 300000); // 5 minutes
    } else {
      throw err;
    }
  });

  // This is an example query to test the connection
  pool.getConnection((err, connection) => {
    if (err) {
      console.error('Error connecting to the database:', err);
      setTimeout(createPool, 300000); // 5 minutes
    } else {
      console.log('Connected to the database');
      if (connection) connection.release();
    }
  });
}

createPool();

module.exports = pool;
© www.soinside.com 2019 - 2024. All rights reserved.