How to get connection status in C # MongoDB v2.0 driver?

We are starting to use the new MongoDB v2 driver , and we cannot understand whether we are connected to db or not.

Code of our repository:

var client = new MongoClient("mongodb://{wrong-host}:{wrong-port}/{dbbname}"); var database = client.GetDatabase(url.DatabaseName); 

Where wrong-host and wrong-port are invalid values.

At first, we thought that an exception would be raised if no one was listening to the specified address, but the driver was not throwing.

The next step was to call the method on db:

 var dbs = client.ListDatabasesAsync().Result.ToListAsync().Result; 

Here we have freez for 30 seconds and than an exception. We did not have to wait 30 seconds to find out that we are connected or not.

System.TimeoutException: timeout after 30,000 ms. server using CompositeServerSelector {Selectors = ReadPreferenceServerSelector {ReadPreference = {Mode = Primary, TagSets = []}}, LatencyLimitingServerSelector {AllowedLatencyRange = 00: 00: 00.0150000}}. The client view of the cluster state is {ClusterId: "1", Type: "Unknown", Status: "Disabled", Servers: [{ServerId: "{ClusterId: 1, EndPoint:" **** "}", EndPoint: " **** ", State:" Disconnected ", Type:" Unknown ", HeartbeatException:" MongoDB.Driver.MongoConnectionException: An exception occurred while opening a connection to the server. ---> System.Net.Sockets.SocketException: connection failed can be performed because the target machine actively abandoned it ******

Finally, we tried to set different timeouts, but nothing changed.

 var client = new MongoClient(new MongoClientSettings { SocketTimeout = TimeSpan.FromSeconds(1), MaxConnectionIdleTime = TimeSpan.FromSeconds(1), MaxConnectionLifeTime = TimeSpan.FromSeconds(1), ConnectTimeout = TimeSpan.FromSeconds(1), Servers = url.Servers }); 

So, the question is, how could we know if we are connected with Mongo or not in a short period of time ~ (1-2) seconds?

[UPD]

Our current solution:

 private IMongoDatabase Connect(string connectionString, TimeSpan timeout) { var url = MongoUrl.Create(connectionString); var client = new MongoClient(url); var db = client.GetDatabase(url.DatabaseName); var pingTask = db.RunCommandAsync<BsonDocument>(new BsonDocument("ping", 1)); pingTask.Wait(timeout); if (pingTask.IsCompleted) log.InfoFormat("Connected to: {0}.", connectionString); else throw new TimeoutException(string.Format("Failed to connect to: {0}.", connectionString)); return db; } 

Using

 database = Connect(connectionString, TimeSpan.FromSeconds(1)); 
+6
source share
2 answers

There is the following workaround for this issue :

 var client = new MongoClient(new MongoClientSettings { Server = new MongoServerAddress("xxxx"), ClusterConfigurator = builder => { builder.ConfigureCluster(settings => settings.With(serverSelectionTimeout: TimeSpan.FromSeconds(10))); } }); 
+3
source

With the new API:

  try { MongoClient client = new MongoClient("xxx"); // if you're running localhost let the parameter empty var db = client.GetDatabase("dbName"); var collection = db.GetCollection<BsonDocument>("collectionName"); var filter1 = Builders<BsonDocument>.Filter.Empty; var filter = new BsonDocument(); var count = 0; using (var cursor = await collection.FindAsync(filter)) { while (await cursor.MoveNextAsync()) { var batch = cursor.Current; foreach (var document in batch) { count++; } } } MessageBox.Show(count.ToString()); } catch(Exception ex) { MessageBox.Show(ex.Message); } 
0
source

Source: https://habr.com/ru/post/988853/


All Articles