本文介绍了MongoServer.State相当于在2.0驱动程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在旧的API(1.X),你可以告诉服务器是否被连接,或者无法使用的 MongoServer 国家属性/ code>例如从返回 MongoClient.GetServer

In the old API (1.X) you could tell whether the server was connected or not by using the State property on the MongoServer instance returned from MongoClient.GetServer:

public bool IsConnceted
{
    get
    {
        return _client.GetServer().State == MongoServerState.Connected;
    }
}

然而 GetServer 不是新的API(2.0)的一部分。这怎么可能实现?

However GetServer is not a part of the new API (2.0). How can that be achieved?

推荐答案

更​​合适的方式来做到这一点是不是通过检查服务器,而是集群(其中可能包含多个服务器),你可以直接访问它的 MongoClient 例如:

The more appropriate way to do that is not by checking the server but rather the cluster (which may contain multiple servers) and you can access it directly from the MongoClient instance:

public bool IsClusterConnceted
{
    get
    {
        return _client.Cluster.Description.State == ClusterState.Connected;
    }
}

如果您想查询的特定服务器也是可能的:

If you would like to check a specific server that's also possible:

public bool IsServerConnceted
{
    get
    {
        return _client.Cluster.Description.Servers.Single().State == ServerState.Connected;
    }
}

请,该值是由最后操作所更新,因此它可能不是最新的。真正确保有一个有效的连接的唯一方法是执行某种操作。

Keep in mind that the value is updated by the last operation so it may not be current. The only way to actually make sure there's a valid connection is to execute some kind of operation.

这篇关于MongoServer.State相当于在2.0驱动程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 03:59