Created
July 1, 2011 15:51
-
-
Save taf2/1058819 to your computer and use it in GitHub Desktop.
mongoose node.js reconnect code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var mongoose = require('mongoose'); | |
var db = mongoose.connect("mongodb://localhost/testdb"); | |
var reconnTimer = null; | |
function tryReconnect() { | |
reconnTimer = null; | |
console.log("try to connect: %d", mongoose.connection.readyState); | |
db = mongoose.connect("mongodb://localhost/testdb"); | |
} | |
mongoose.connection.on('opening', function() { | |
console.log("reconnecting... %d", mongoose.connection.readyState); | |
}); | |
mongoose.connection.on('open', function() { | |
console.log("connected"); | |
if (reconnTimer) { clearTimeout(reconnTimer); reconnTimer = null; } | |
}); | |
mongoose.connection.db.on('close', function() { | |
console.log("disconnected"); | |
mongoose.connection.readyState = 0; // force... | |
mongoose.connection.db.close(); // removeAllListeners("reconnect"); | |
if (reconnTimer) { | |
console.log("already trying"); | |
} | |
else { | |
reconnTimer = setTimeout(tryReconnect, 500); // try after delay | |
} | |
}); | |
process.on('SIGINT', process.exit.bind(process)); | |
setInterval(function() { | |
console.log('alive: %d', mongoose.connection.readyState); | |
},2500); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@lauramorillo,
I am using setTimeout to continuously try to connect on disconnect.
ex:
instance.connection.on("disconnected", () => {
console.log("Databse disconnected: ");
if (connected) {
connected = false;
console.log("After disconnect");
tryPersistentDbConnection(dbSettings, connectUrl, mongoose, { server: { auto_reconnect: false } });
}
});
private static tryPersistentDbConnection(dbSettings, connectUrl, mongoose, options) {
var instance = mongoose.connect(connectUrl, options, function (err) {
if (err) {
console.log("Error connecting. Error Message: " + err.message);
console.log("------------Trying to reconnect------------------");
setTimeout(function () {
//call itself on failure
tryPersistentDbConnection(dbSettings, connectUrl, mongoose, options)
}, 25000)
}
});
}