MongoServer.State equivalent in the 2.0 driver

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-28 06:52:05

问题


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;
    }
}

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


回答1:


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.




回答2:


As noted by i3arnon, one has to perform some sort of operation on the database before the state is updated properly.

The act of enumerating the databases is sufficient to update the state.

This worked for me:

var databases = _client.ListDatabasesAsync().Result;
databases.MoveNextAsync(); // Force MongoDB to connect to the database.

if (_client.Cluster.Description.State == ClusterState.Connected)
{
    // Database is connected.
}


来源:https://stackoverflow.com/questions/29459990/mongoserver-state-equivalent-in-the-2-0-driver

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