7

如何Ping使用新的 C# 驱动程序 2.0 调用命令?
在旧驱动程序中,它可以通过Server.Ping()? 另外,有没有办法在不运行实际查询的情况下找出服务器是否正在运行/响应?
使用mongoClient.Cluster.Description.State无济于事,因为即使在 mongo 服务器开始响应之后,它仍然处于断开状态。

4

3 回答 3

3

Description您可以使用其属性检查集群的状态:

var state = _client.Cluster.Description.State

如果您想要该集群中的特定服务器,您可以使用以下Servers属性:

var state = _client.Cluster.Description.Servers.Single().State;
于 2015-06-08T15:50:29.857 回答
2

这在 c# 驱动程序 2 和 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");
            }
        }
于 2015-09-04T08:52:50.950 回答
0

正如@i3arnon 的回答,我可以说这对我来说是可靠的:

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

或在 .Net 的新版本中

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

但是如果你真的想运行一个 ping 命令,你可以这样做:

var command = new CommandDocument("ping", 1);
try
{
    db.RunCommand<BsonDocument>(command);
}
catch (Exception ex)
{
    // ping failed
}
于 2016-12-21T13:32:37.763 回答