检查MongoDB服务器是否在不知道任何数据库的情况下启动

mm9b1k5b  于 2022-11-28  发布在  Go
关注(0)|答案(3)|浏览(137)

我正在为一个应用程序创建一个MongoDB连接器,我想知道是否有可能在不知道任何数据库的情况下检查MongoDB服务器是否已启动。
到目前为止,我看到的每个示例都需要知道MongoDB服务器上的过时方法或数据库。
下面是我尝试做的一个例子;
How to check connection to mongodb
我想到的一种方法是使用;

ListDatabaseNames()

捕获任何与连接失败相关的异常。2然而,这似乎是一个“肮脏”的解决方案,因为我还必须捕获所有与无效权限相关的异常才能运行命令。
或许,我想做的事情,并没有什么意义,如果是这样的话,请说!

2ic8powd

2ic8powd1#

查看以下堆栈溢出后提交;
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;
}

这应该可以处理任何权限问题,因为即使用户实际上没有运行的权限,它也应该返回connected;

client.ListDatabaseNames();

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

e4eetjau

e4eetjau2#

mongodb的Ping命令有一个c#实现。
如此处所述-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驱动程序中查看可用的类。

p5fdfcr1

p5fdfcr13#

我能够利用ICluster接口的DescriptionChanged事件(由MongoClient.Cluster属性getter返回):

private Task WaitForClusterStartup(ICluster cluster)
{
    var tcs = new TaskCompletionSource();

    cluster.DescriptionChanged += (sender, args) =>
    {
        if (args.NewClusterDescription.State == ClusterState.Connected)
        {
            tcs.SetResult();
        }
    };

    return tcs.Task;
}

相关问题