我正在为应用程序创建MongoDB连接器,想知道是否可以在不知道任何数据库的情况下检查MongoDB服务器是否已启动。
到目前为止,我看到的每个示例都要求知道不赞成使用的方法或MongoDB服务器上的数据库。
下面是我正在尝试做的事的一个例子;
How to check connection to mongodb
我想到的一种方法是使用;
ListDatabaseNames()
捕获与连接失败有关的所有异常。但是,这似乎有点“肮脏”的解决方案,因为我还必须捕获所有与无效权限有关的异常以运行命令。
也许,我想做的事没有意义。如果是这样,请说!!
答案 0 :(得分:0)
mongodb的c#
命令有一个Ping
实现。
如此处所述-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驱动程序中的可用类。
答案 1 :(得分: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不为空。