检查是否MongoDB的服务器是没有学会任何数据库

问题描述 投票:1回答:2

我创建了一个应用程序MongoDB的连接器,并想知道是否有可能来检查的MongoDB服务器是没有学会任何数据库。

到目前为止,我所看到的每一个例子需要过时的方法或MongoDB服务器上的数据库是已知的。

什么我想要做的可以看到下面的一个例子;

How to check connection to mongodb

一种方法我想过这样做是为了使用;

ListDatabaseNames()

醒目,涉及到的连接失败的任何异常。然而,这似乎有点像一个“脏”的溶液,作为我也必须赶上与无效permssions运行该命令的所有异常。

也许,我想要做的,是没有意义的。如果是这样的话,请说!

c# mongodb
2个回答
0
投票

有一个c#实施Ping的MongoDB命令。

这里描述 - http://mongodb.github.io/mongo-csharp-driver/2.7/apidocs/html/T_MongoDB_Driver_Core_Operations_PingOperation.htm,PingOperation是MongoDB.Driver.Core组装功能。

您应该能够使用类似的东西 -

public void Ping()
{
    var messageEncoderSettings = GetMessageEncoderSettings();
    var operation = new PingOperation(messageEncoderSettings);

    var server = GetServer();
    using (var channelSource = new ChannelSourceHandle(new ServerChannelSource(server)))
    using (var channelSourceBinding = new ChannelSourceReadWriteBinding(channelSource, ReadPreference.PrimaryPreferred))
    {
        operation.Execute(channelSourceBinding, CancellationToken.None);
    }
}

来源:C# Example

这也取决于你所使用的驱动程序。我会建议寻找到可用的类在你的MongoDB驱动程序。


0
投票

看着下面的堆栈溢出后提交;

MongoServer.State equivalent in the 2.0 driver

C# MongoDB.Driver GetServer is Gone, What Now?

How to check connection to mongodb

我已经认识到,这是不是真的可以直接ping服务器/集群。为了解决这个问题,我也做了以下内容:

public bool checkConnection(string connection_string)
{
    var client = new MongoClient(connection_string)

    try 
    {
        client.ListDatabaseNames();
    }
    catch (Exception)
    {
    }

    return client.Cluster.Description.State == ClusterState.Connected;
}

这应该处理任何权限问题,因为它应该返回连接即使用户并不实际拥有运行权限;

client.ListDatabaseNames();

如果使用以上,应进行额外的检查,以确保MongoClient不为空。

© www.soinside.com 2019 - 2024. All rights reserved.