在MongoDB驱动程序中侦听重新连接事件

Sam*_* E. 3 mongodb node.js

我想将事件监听器添加到MongoDB连接,以便在连接断开,每次重新连接尝试以及成功重新连接尝试时运行.

我阅读了所有官方文档和API,但我找不到解决方案.

目前,我有这个,但只有超时事件有效.//如果我们还没有初始化'MongoClient',请初始化一个并保存它.if(!this.client)this.client = new MongoClient();

    this.connection = await this.client.connect(connectionString, this.settings);

    this.client.server.on('connect', event => {
        console.log(event);
    });

    this.client.server.on('error', event => {
        console.log(event);
    });

    this.client.server.on('reconnect', event => {
        console.log(event);
    });

    this.client.server.on('connections', event => {
        console.log(event);
    });

    this.client.server.on('timeout', event => {
        console.log(event);
    });

    this.client.server.on('all', event => {
        console.log(event);
    });
Run Code Online (Sandbox Code Playgroud)

我尝试了这里列出的事件,但它们有效,但没有"重新连接"事件:http: //mongodb.github.io/node-mongodb-native/2.2/reference/management/sdam-monitoring/

Nei*_*unn 6

你当然可以.基本上,虽然您需要在较低级别上接收EventEmitter而不是基本上离开它MongoClient自己.

你可以清楚地看到这些东西存在,因为它们在"日志记录"中可见,可以通过以下设置在驱动程序中打开:

{ "loggerLevel": "info" }
Run Code Online (Sandbox Code Playgroud)

从那时起,它实际上只需要进入实际的源发射器.我已经在下面的列表中完成了这些,并且包括一个小技巧,用于从给定的发出中获取枚举事件,这被我自己用来跟踪它:

const MongoClient = require('mongodb').MongoClient;

function patchEmitter(emitter) {
  var oldEmit = emitter.emit;

  emitter.emit = function() {
    var emitArgs = arguments;

    console.log(emitArgs);

    oldEmit.apply(emitter, arguments);
  }

}


(async function() {

  let db;

  try {

    const client = new MongoClient();

    client.on('serverOpening', () => console.log('connected') );

    db = await client.connect('mongodb://localhost/test', {
      //loggerLevel: 'info'
    });

    //patchEmitter(db.s.topology);

    db.s.topology.on('close', () => console.log('Connection closed') );
    db.s.topology.on('reconnect', () => console.log('Reconnected') );


  } catch(e) {
    console.error(e)
  }

})()
Run Code Online (Sandbox Code Playgroud)

所以这两个听众定义了:

    db.s.topology.on('close', () => console.log('Connection closed') );
    db.s.topology.on('reconnect', () => console.log('Reconnected') );
Run Code Online (Sandbox Code Playgroud)

当连接断开并且实现重新连接时,将会触发.还有其他一些事情,例如重新连接尝试,它们也在事件发射器中,就像您在loggerLevel打开设置时看到的那样.