如何检测mongodb重新连接失败事件 [英] How can I detect mongodb reconnect failed event

查看:292
本文介绍了如何检测mongodb重新连接失败事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的应用程序中使用了nodejs mongo驱动程序.我在连接中设置了以下选项:

I am using nodejs mongo driver in my application. I set up below options in the connection:

{
  connectTimeoutMS: 30000,
  socketTimeoutMS: 30000,
  // retry to connect for 120 times
  reconnectTries: 120,
  // wait 1 second before retrying
  reconnectInterval: 1000
};

如果连接断开,它将尝试重新连接120次,每次延迟1秒.我需要在重新连接期间监听服务器状态变化.我在事件监听器下方添加了以下内容:

It will try to re-connect 120 times if the connection is broken and 1 second for each delay. I need to listen on the server status changes during re-connect. I added below event listeners:

db.on('close', this.onClose.bind(this));
db.on('error', this.onError.bind(this));
db.on('timeout', this.onTimeout.bind(this));
db.on('parseError', this.onParseError.bind(this));
db.on('reconnect', this.onReconnect.bind(this));

所有事件侦听器都工作正常,但是我的问题是在重试120次后如何检测到重新连接失败.例如,如果服务器关闭,那么我将收到关闭事件.如果服务器在120秒内启动,我将收到重新连接事件.但是,如果服务器在120秒内没有启动怎么办.我如何检测到这种变化?我应该自己实施吗?

All the event listeners are working fine but my problem is how to detect that the reconnect failed after 120 times retries. For example, if the server is down then I will receive a close event. If the server is up during 120 seconds, I will receive reconnect event. But what if the server is not up in 120 seconds. How can I detect this change? Should I implement it by myself?

推荐答案

您可以这样做:

// Do this on your global scope //
var connectionAttemps = 0;

var doThisInsideYourTriggeredErrorEvent = function () {
    connectionAttemps++;

    if (connectionAttemps >= 120)
    {
        // Here goes your logic to stop the reconnection attempts //
    }
    /* Here goes your implemented logic (if any) for the "onError" event */
}

检查是否有帮助.

PS:请注意, my 函数的内容位于 OnError 函数的内容之内.

PS: note that the content of my function goes inside the content of your OnError function.

这篇关于如何检测mongodb重新连接失败事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆