简体   繁体   English

如何检查C#中的MongoDB连接是否有效?

[英]How do you check if MongoDB connection is alive in C#?

How do you check if MongoDB connection is alive using the latest 2.0 .NET MongoDB Driver? 如何使用最新的2.0 .NET MongoDB驱动程序检查MongoDB连接是否有效? Please don't include solutions using the legacy driver. 请不要包括使用旧版驱动程序的解决方案。 Thanks. 谢谢。

I used to use the Ping method but that may eventually become obsolete (placed in the Legacy dll since 2.0 release): http://api.mongodb.org/csharp/current/html/M_MongoDB_Driver_MongoServerInstance_Ping.htm 我曾经使用过Ping方法,但最终可能会过时(自2.0版本开始放置在旧版dll中): http : //api.mongodb.org/csharp/current/html/M_MongoDB_Driver_MongoServerInstance_Ping.htm

There are a couple of things you can do. 您可以做几件事。

  1. You can check your MongoClient's Cluster.Description property which gives you an indication of the health of the entire cluster. 您可以检查MongoClient的Cluster.Description属性,该属性可以指示整个群集的运行状况。

  2. Alternatively, you can run the ping command manually. 或者,您可以手动运行ping命令。 The problem with doing this is that it is only going to ping 1 server and if you are looking for health of the entire cluster, then. 这样做的问题在于,它只会对1台服务器执行ping操作,并且如果您正在寻找整个群集的运行状况,那么。

    await client.GetDatabase("admin").RunCommandAsync(new BsonDocument("ping", 1)) 等待client.GetDatabase(“ admin”)。RunCommandAsync(new BsonDocument(“ ping”,1))

  3. Not worry about it. 不用担心。 The driver is handling the situations where failover is happening and, in many cases, will wait for the failover to happen prior to running your operation. 驱动程序正在处理发生故障转移的情况,在许多情况下,驱动程序将等待故障转移发生,然后再运行操作。

Perhaps if you elaborated on your need, I could provide a better answer. 也许如果您详细说明了您的需求,我可以提供更好的答案。

So after going through the documentation, i did not find anything equivalent to ping. 因此,在阅读了文档之后,我没有找到与ping等效的任何内容。 The only other solution i see is to execute a simple operation and see if it fails. 我看到的唯一其他解决方案是执行一个简单的操作,然后查看它是否失败。 Try something like: 尝试类似:

db.getName()

If that fails, you know the connection has been dropped. 如果失败,则说明连接已断开。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM