【问题标题】:How to change required connection after require()require() 后如何更改所需的连接
【发布时间】:2019-09-11 14:25:57
【问题描述】:

在我目前正在处理的 Node.js 项目中,mysql 服务器会在一段时间后关闭连接。我实现了一个错误处理程序,在这种连接丢失后重新连接。错误处理有效,但我无法找到一种方法来获取在使用新连接之前已经需要连接的文件。

我已经尝试删除缓存,但这并不能解决我的问题。

var mysql = require('mysql');
var mysqlConfig = require('./mysqlConfig');
var connection;

function handleDisconnect() {
    connection = mysql.createConnection(mysqlConfig.db);

    connection.connect((err) => {
        if (err) {
            console.log("error on connection to Database: " + err);
            setTimeout(handleDisconnect, 1000);
        }
    });

    connection.on('error', (err) => {
        delete require.cache[require.resolve('./db.js')]; //this module
        if (err.code === 'PROTOCOL_CONNECTION_LOST') {
            handleDisconnect();
        } else {
            throw err;
        }
    });
}

handleDisconnect();

module.exports = connection;

以下是需要此模块的文件示例:

var db = require('../db');
var connector = {};

connector.GetStuff = function(query) {
    return new Promise((resolve, reject) => {
        let response = {};
        db.query(query, (error, results, fields) => {
            if (error) throw error;
            if (results && results.length > 1) {
                response = results[0];
                resolve(response);
            }
        })
    })
}

我想只用新的替换之前需要的连接对象。但实际上我的应用程序崩溃并出现以下错误:

Error: Cannot enqueue Query after fatal error.

请不要告诉我只为每个查询打开一个新连接。这是一个我不能使用的概念,因为客户希望。

【问题讨论】:

    标签: javascript mysql node.js node-modules


    【解决方案1】:

    一个好的解决方案是不导出第一个文件中的连接对象,而是导出一些包装器或容器,其内容由连接故障处理函数定期更新。

    class ConnectionContainer {
      setConnection(connection) {
        this.connection = connection;
      }
    
      getCurrentConnection() {
        return this.connection;
      }
    }
    
    const connectionContainer = new ConnectionContainer();
    
    function handleDisconnect() {
        const connection = mysql.createConnection(mysqlConfig.db);
    
        connection.connect((err) => {
            if (err) {
                console.log("error on connection to Database: " + err);
                return setTimeout(handleDisconnect, 1000);
            } else {
              container.setConnection(connection); // set a new connection once it's connected
            }
        });
    
        connection.on('error', (err) => {
            delete require.cache[require.resolve('./db.js')]; // I don't think you need this anymore
            if (err.code === 'PROTOCOL_CONNECTION_LOST') {
                handleDisconnect();
            } else {
                throw err;
            }
        });
    }
    
    handleDisconnect();
    
    module.exports.connectionContainer = connectionContainer;
    
    // and in the connector file you could go like this:
    
    const { connectionContainer } = require('../db'); // you might need a better name here for the file
    
    //...
    connectionContainer.getCurrentConnection().query(query, () => {});
    

    【讨论】:

      猜你喜欢
      • 2023-03-27
      • 2018-11-29
      • 1970-01-01
      • 1970-01-01
      • 2022-10-13
      • 2021-12-29
      • 1970-01-01
      • 2019-09-07
      • 1970-01-01
      相关资源
      最近更新 更多