How in the code to check the connection to the MongoDB server from the C # code?
When I want to insert data or pick it up from MongoDB , and the server is not running, then the program just hangs.
But I don’t know how to prevent it.
Use the MongoClient Ping MongoClient
var connectionString = "mongodb://localhost"; var client = new MongoClient(connectionString); var server = client.GetServer(); try { server.Ping(); } catch(Exception) { // сервер недоступен } server.Ping(); wrap in try/catch ?) - tCodetry { server.Ping(); } catch(Exception){} string try { server.Ping(); } catch(Exception){} try { server.Ping(); } catch(Exception){} falls in Exception Подключение не установлено, т.к. конечный компьютер отверг запрос на подключение 127.0.0.1:27017 Подключение не установлено, т.к. конечный компьютер отверг запрос на подключение 127.0.0.1:27017 and therefore if the server is running, then the Exception will not be - tCodeChecks whether the server is alive (throws an exception if not). , if the server is available then there will be no error, if unavailable get exception - tCodeYou can check the connection to the MongoDB server using the following code:
public async Task<bool> CheckMongoConnection() { try { var databases = _client.ListDatabasesAsync().Result; await databases.MoveNextAsync(); return _client.Cluster.Description.State == ClusterState.Connected; } catch (Exception mce) { await Console.Error.WriteLineAsync(mce.Message); return false; } } You can write a synchronous version of the verification, similar to this code, but who needs it?
It is advisable to create a MongoClient with settings such that checking with the server turned off lasts ~ 5-6 seconds:
_clientSettings = new MongoClientSettings { Server = _mongoUrl.Server, ServerSelectionTimeout = TimeSpan.FromSeconds(5) }; ServerSelectionTimeout defaults to something like 30+ seconds. So the response will be much faster. But, proceed from your needs.
Source: https://ru.stackoverflow.com/questions/649190/
All Articles