Created
May 7, 2013 23:10
-
-
Save craiggwilson/5536920 to your computer and use it in GitHub Desktop.
Testing .NET MongoDB Driver Replica Set Failover
This file contains hidden or 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
using System; | |
using System.Collections.Generic; | |
using System.Configuration; | |
using System.Diagnostics; | |
using System.IO; | |
using System.Linq; | |
using System.Threading; | |
using MongoDB.Bson; | |
using MongoDB.Bson.IO; | |
using MongoDB.Bson.Serialization; | |
using MongoDB.Bson.Serialization.Serializers; | |
using MongoDB.Driver; | |
using MongoDB.Driver.Builders; | |
namespace MongoDB.DriverUnitTests.Jira | |
{ | |
public static class Program | |
{ | |
private static object _consoleLock = new object(); | |
public static void Main() | |
{ | |
var server = new MongoClient("mongodb://localhost:30000/?replicaset=test").GetServer(); | |
var c = server.GetDatabase("foo").GetCollection("bar"); | |
ClearData(c); | |
InsertData(c); | |
for (int i = 0; i < 3; i++) | |
{ | |
ThreadPool.QueueUserWorkItem(_ => DoWork(c)); | |
} | |
DoWork(c); // blocking | |
} | |
private static void ClearData(MongoCollection<BsonDocument> c) | |
{ | |
c.Database.Drop(); | |
} | |
private static void InsertData(MongoCollection<BsonDocument> c) | |
{ | |
for (int i = 0; i < 10000; i++) | |
{ | |
c.Insert(new BsonDocument("i", i)); | |
} | |
} | |
private static void DoWork(MongoCollection<BsonDocument> c) | |
{ | |
var rand = new Random(); | |
while (true) | |
{ | |
var i = rand.Next(0, 10000); | |
BsonDocument doc; | |
try | |
{ | |
doc = c.FindOne(new QueryDocument("i", i)); | |
Console.Write("."); | |
} | |
catch (Exception ex) | |
{ | |
lock (_consoleLock) | |
{ | |
Console.ForegroundColor = ConsoleColor.Red; | |
Console.Write("."); | |
Console.ForegroundColor = ConsoleColor.White; | |
} | |
continue; | |
} | |
if (doc == null) | |
{ | |
try | |
{ | |
c.Insert(new BsonDocument().Add("i", i)); | |
Console.Write("+"); | |
} | |
catch (Exception ex) | |
{ | |
lock (_consoleLock) | |
{ | |
Console.ForegroundColor = ConsoleColor.Red; | |
Console.Write("+"); | |
Console.ForegroundColor = ConsoleColor.White; | |
} | |
} | |
} | |
else | |
{ | |
try | |
{ | |
var query = new QueryDocument("_id", doc["_id"]); | |
var update = new UpdateDocument("$set", new BsonDocument("i", i + 1)); | |
c.Update(query, update, UpdateFlags.Multi); | |
Console.Write("+"); | |
} | |
catch (Exception ex) | |
{ | |
lock (_consoleLock) | |
{ | |
Console.ForegroundColor = ConsoleColor.Red; | |
Console.Write("+"); | |
Console.ForegroundColor = ConsoleColor.White; | |
} | |
} | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment