MongoDB Driver 2.0 C# is there a way to find out if the server is down? In the new driver how do we run the Ping command?

好久不见. 提交于 2019-12-01 17:41:20

问题


How do you call the Ping command with the new C# driver 2.0?
In the old driver it was available via Server.Ping()? Also, Is there a way to find out if the server is running/responding without running the actual query?
Using mongoClient.Cluster.Description.State doesn't help because it still gave the disconnected state even after the mongo server started responding.


回答1:


You can check the cluster's status using its Description property:

var state = _client.Cluster.Description.State

If you want a specific server out of that cluster you can use the Servers property:

var state = _client.Cluster.Description.Servers.Single().State;



回答2:


This worked for me on both c# driver 2 and 1

int count = 0;
var client = new MongoClient(connection);
        // This while loop is to allow us to detect if we are connected to the MongoDB server
        // if we are then we miss the execption but after 5 seconds and the connection has not
        // been made we throw the execption.
        while (client.Cluster.Description.State.ToString() == "Disconnected") {
            Thread.Sleep(100);
            if (count++ >= 50) {
                throw new Exception("Unable to connect to the database. Please make sure that "
                    + client.Settings.Server.Host + " is online");
            }
        }



回答3:


As @i3arnon's answer I can tell it was reliable for me in this way:

var server = client.Cluster.Description.Servers.FirstOrDefault();
var serverState = ServerState.Disconnected;
if (server != null) serverState = server.State;

or in new versions of .Net

var serverState = client.Cluster.Description.Servers.FirstOrDefault()?.State 
    ?? ServerState.Disconnected;

But if you realy want to run a ping command you can do it like this:

var command = new CommandDocument("ping", 1);
try
{
    db.RunCommand<BsonDocument>(command);
}
catch (Exception ex)
{
    // ping failed
}


来源:https://stackoverflow.com/questions/30713599/mongodb-driver-2-0-c-sharp-is-there-a-way-to-find-out-if-the-server-is-down-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!