How to Get the Server Address of the server that data is pulled from

大兔子大兔子 提交于 2019-12-12 18:34:41

问题


I know we have it in Java driver using cursor.getServerAddress(). However, I couldn't find any relevant call in C#.


回答1:


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).

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.

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

Documentation

However, in your case you can also get it from the cursor via the Server property:

cursor.Server.Instance.Address.Host

or

cursor.Server.Instances[] 

Cursor Server Documentation

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.



来源:https://stackoverflow.com/questions/15886784/how-to-get-the-server-address-of-the-server-that-data-is-pulled-from

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!