Last active
August 29, 2015 14:03
-
-
Save saintc0d3r/5778c1609bae58b04716 to your computer and use it in GitHub Desktop.
[MongoDb][Node.js] A simple demo to demonstrate Mongodb Replica Set's failover capability.
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
/** | |
* A sample demo to demonstrate Mongodb Replica Set's failover capability. | |
* Instructions: | |
* 1. Run your replica set servers. | |
* 2. Run this app (note: adjust the replica set's hosts & ports as you see them fit in your environments.) | |
* 3. Shutdown your replica set's primary node. | |
* 4. Watch the outputs of this running app. Confirm that the inserts are defered ( no errors being throws) when the primary node is downed and | |
* then come up again after a new primary node is elected in the replica set. | |
*/ | |
var MongoClient = require('mongodb').MongoClient; | |
var assert = require('assert'); | |
// Notice the difference of connection string for connecting to a replica set and the usual one for connecting to a single mongodb server, | |
var connection_string = "mongodb://127.0.0.1:27018, 127.0.0.1:27019, 127.0.0.1:27020/demo_replica_set"; | |
MongoClient.connect(connection_string, function(err, db){ | |
if (err) throw err; | |
var document_value = 0; | |
function insertDocument(){ | |
document_value++; | |
var test_docs = db.collection("test_docs"); | |
test_docs.insert({'value':document_value}, function(err, inserted){ | |
if (err) throw err; | |
console.log("[INFO] - Successfully inserted "+JSON.stringify(inserted)+" document."); | |
}); | |
console.log("[INFO] - Dispatched insert operation..."); | |
// Delayed for 1 sec then dispatch another insert. | |
setTimeout(insertDocument, 1000); | |
} | |
insertDocument(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment