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



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

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

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

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; }        
}

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

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

以下是详细错误

System.TimeoutException HResult=0x80131505 消息=使用 CompositeServerSelector{ Selectors = MongoDB.Driver.MongoClient+AreSessionsSupportedServerSelector, LatencyLimitingServerSelector{ AllowedLatencyRange = 00:00:00.0150000 } } 选择服务器后发生超时。群集状态的客户端视图为

{ 群集 ID : "1", 连接模式 : "副本集", 类型 : "副本集", 状态 : "断开连接", 服务器 : [{ 服务器 ID: "{ 群集 ID : 1,

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

这张JIRA票有详细信息:https://jira.mongodb.org/browse/CSHARP-1160

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

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

希望对您有所帮助。

很明显,您没有在连接代码中添加数据库名称。

下面是连接字符串的模板

`var client = new MongoClient("mongodb://<dbuser>:<dbuserpassword>@<mongoaddress>/<dbname>?connect=replicaSet&ssl=true&replicaSet=<replicaset>&authSource=<authsource>");
var database = client.GetDatabase("test");`

您需要填写以下内容

  • 数据库用户:用户的用户名
  • 数据库用户
  • 密码:数据库用户的密码
  • 数据库
  • 名称:数据库的名称
  • 蒙戈地址
  • :蒙戈布碎片的地址
  • 副本集
  • :副本集的名称
  • 身份验证
  • 源:身份验证源

相关内容

最新更新