如何获取从中提取数据的服务器的服务器地址 [英] How to Get the Server Address of the server that data is pulled from
问题描述
我知道我们在Java驱动程序中使用cursor.getServerAddress()拥有了它.但是,我在C#中找不到任何相关的调用.
I know we have it in Java driver using cursor.getServerAddress(). However, I couldn't find any relevant call in C#.
推荐答案
不幸的是,在深入研究了C#驱动程序源代码(以及Java源代码以了解其作用)之后,实际的服务器地址用作提取的一部分被作为私有成员(_serverInstance
)隐藏在Enumerator中.
Unfortunately, after digging a little deeper though through the C# driver source code (and the Java source code to see what it was doing), the actual server address that was used as part of the fetch is hidden away in the Enumerator as a private member (_serverInstance
).
尤其是,它隐藏在名为MongoCursorEnumerator
的类中.不幸的是,没有一种诚实"的方式来做到这一点.我想可以使用.NET反射来实现它,但这通常不是一个好主意,尤其是对于您不拥有的代码.如果您想要驱动程序的自定义派生,则可以轻松地将其添加为新属性.您可能要在此处添加问题.
In particular, it's hidden away in a class called the MongoCursorEnumerator
. Unfortunately, there isn't an "honest" way of getting to it. You could use .NET reflection I suppose to get to it, but that's generally not a good idea, especially with code you don't own. If you wanted to have a custom fork of the driver, you could easily add it as a new property. You might want to add an issue here.
通常,您可以获取MongoDB连接使用的实例,因为它们在MongoServerInstance
类的Address
属性中可用.
In general, you can get the instances used by the MongoDB connection, as they are available on the MongoServerInstance
class, the Address
property.
var client = new MongoClient();
var server = client.GetServer();
// server.Instance.Address
但是,您也可以通过Server
属性从cursor
中获取它:
However, in your case you can also get it from the cursor
via the Server
property:
cursor.Server.Instance.Address.Host
或
cursor.Server.Instances[]
有趣的是,当有多个实例可用时,C#驱动程序将引发异常.因此,如果您不知道有多少实例,则需要处理exception
(InvalidOperationException
),或者始终使用Instances[]
属性来返回关联的实例.
The C# driver interestingly throws and exception when more than one Instance is available. So, if you don't know how many instances there are, you either need to handle the exception
(InvalidOperationException
), or always use the Instances[]
property to return the associated instances.
这篇关于如何获取从中提取数据的服务器的服务器地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!