Created
August 25, 2016 11:29
-
-
Save bruno-garcia/5b9c2e517dca419a018bff82c340fb24 to your computer and use it in GitHub Desktop.
MongoDB C# Driver reconnection issue
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
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Threading; | |
using System.Threading.Tasks; | |
using MongoDB.Bson; | |
using MongoDB.Driver; | |
namespace MongoClientReconnectIssue | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var hosts = new[] | |
{ | |
"abc-mdb-node1.network.com", // Start with: Primary | |
"abc-mdb-node2.network.com", // Start with: Secondary | |
"abc-mdb-node3.network.com" // Start with: Secondary | |
}; | |
var db = GetDb(hosts); | |
var source = new CancellationTokenSource(); | |
var token = source.Token; | |
Task.Run(async () => | |
{ | |
while (!token.IsCancellationRequested) | |
{ | |
string message = null; | |
try | |
{ | |
dynamic result = await db.RunCommandAsync((Command<BsonDocument>)"{ replSetGetStatus: 1 }", cancellationToken: token); | |
IEnumerable<dynamic> values = result["members"]; | |
message = string.Join(Environment.NewLine, values.Select(member => | |
{ | |
string nodeInfo; | |
try | |
{ | |
nodeInfo = $"Ping: {member["pingMs"]}"; | |
} | |
catch (KeyNotFoundException) | |
{ | |
nodeInfo = $"Self: {member["self"]}"; | |
} | |
return $"{member["name"]}:{member["stateStr"]}, {nodeInfo}"; | |
})); | |
} | |
catch (Exception ex) | |
{ | |
message = ex.Message; | |
db = GetDb(hosts); | |
} | |
finally | |
{ | |
Console.Clear(); | |
Console.WriteLine(message); | |
await Task.Delay(500, token); | |
} | |
} | |
}, token); | |
Console.ReadKey(); | |
source.Cancel(); | |
} | |
private static IMongoDatabase GetDb(string[] host) | |
{ | |
var servers = host.Select(h => new MongoServerAddress(h)).ToList(); | |
var client = new MongoClient(new MongoClientSettings | |
{ | |
WriteConcern = WriteConcern.WMajority, | |
Servers = servers | |
}); | |
return client.GetDatabase("admin"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment