使用 C# 访问 Azure 中的 MongoDB 时选择服务器 30000 毫秒后发生超时

prv*_*rvn 6 c# timeout azure mongodb

.Net 控制台应用程序在 4.6.1 框架中,使用 MongoDB.Driver 2.8.0。我在 SO 中引用了许多帖子,但我仍然收到超时错误。下面是我参考的一些帖子

使用 CompositeServerSelector System.TimeoutException 选择服务器 30000 毫秒后发生超时:使用 CompositeServerSelector MongoDB C# 2.0 TimeoutException选择服务器 30000 毫秒后发生超时

下面是我用来从集合中访问文档的代码。

using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver;

class Program
{
    static void Main(string[] args)
    {
        string connectionString =
            @"mongodb://mongoaccnt:ADASDXZWADAS2VgsqTYcTS4gtADmB1zQ==@mongocnt.documents.azure.com:10255/?ssl=true&replicaSet=globaldb";

        MongoClientSettings settings = MongoClientSettings.FromUrl(
          new MongoUrl(connectionString)
        );

        settings.SslSettings = new SslSettings() { EnabledSslProtocols = SslProtocols.Tls12 };

        var mongoClient = new MongoClient(settings);
        string dbName = "app-db";
        string collectionName = "test";
        var database = mongoClient.GetDatabase(dbName);


        var todoTaskCollection = database.GetCollection<test>(collectionName);

        var filter = Builders<test>.Filter.Eq("name", "second");

        var results = todoTaskCollection.Find(filter).ToList();

        Console.WriteLine(results);
        Console.ReadLine();
    }

}

public class test
{
    public string name { get; set; }        
}
Run Code Online (Sandbox Code Playgroud)

以下是 Azure 云门户中显示的数据

db.test.find()
Operation consumed 2.31 RUs
{ "_id" : ObjectId("5ca4949fd59b290e00e35eda"), "id" : 1, "name" : "first" }
{
    "_id" : ObjectId("5caafe968f678e0f504c6e64"),
    "id" : 2,
    "name" : "second"
}
Run Code Online (Sandbox Code Playgroud)

下面是详细的错误

System.TimeoutException HResult=0x80131505 Message=使用 CompositeServerSelector 选择服务器 30000 毫秒后发生超时{ Selectors = MongoDB.Driver.MongoClient+AreSessionsSupportedServerSelector, LatencyLimitingServerSelector{ AllowedLatencyRange = 00:00:00.015.000000 集群状态的客户端视图为 { ClusterId : "1", ConnectionMode : "ReplicaSet", Type : "ReplicaSet", State : "Disconnected", Servers : [{ ServerId: "{ ClusterId : 1,

Moh*_*rma 2

您是否尝试过在连接字符串后添加“?connect=replicaSet”:

此 JIRA 票证包含详细信息:https://jira.mongodb.org/browse/CSHARP-1160

实际上,他们区分了连接到独立服务器和直接连接到副本集成员,后者相对不常见。不幸的是,MongoLab 的单节点设置实际上是单节点副本集,这导致我们不信任它。您可以通过将 ?connect=replicaSet 附加到连接字符串来解决此问题。它将强制驱动程序进入副本集模式,一切都会正常工作。

您可以在以下位置找到更多详细信息:https://groups.google.com/forum/#! topic/mongodb-csharp/O460OHiFjZs

希望能帮助到你。