Reputation: 325
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
};
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));
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?
Upvotes: 1
Views: 1959
Reputation: 210
There is a (somewhat) undocumented event type: reconnectFailed
.
This is documented here: http://mongodb.github.io/node-mongodb-native/core/api/Server.html#event:reconnectFailed but only for the Server object. However it does seem to also be emitted by the Db object, like so:
db.on('reconnectFailed', (err) => {
// do something here
});
I've verified this works also for the 2.2 version of the nodejs mongodb driver, just not documented there at all.
Upvotes: 2
Reputation: 338
You can do it like this:
// 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 */
}
Check if it helps.
PS: note that the content of my function goes inside the content of your OnError function.
Upvotes: 1