8

我们开始使用新的MongoDB 驱动程序 v2,我们无法理解我们是否连接到数据库。

我们的存储库代码:

var client = new MongoClient("mongodb://{wrong-host}:{wrong-port}/{dbbname}");
var database = client.GetDatabase(url.DatabaseName);

其中wrong-hostwrong-port是无效值。

首先,我们认为如果没有人在指定地址上监听但驱动程序没有抛出异常,则会引发异常。

下一步是在数据库上调用方法:

var dbs = client.ListDatabasesAsync().Result.ToListAsync().Result;

在这里,我们冻结了 30 秒而不是异常。我们不适合等待 30 秒来了解我们是否连接。

System.TimeoutException:使用 CompositeServerSelector{ Selectors = ReadPreferenceServerSelector{ ReadPreference = { Mode = Primary, TagSets = [] } },LatencyLimitingServerSelector{ AllowedLatencyRange = 00:00:00.0150000 } } 选择服务器 30000 毫秒后发生超时。集群状态的客户端视图是 { ClusterId : "1", Type : "Unknown", State : "Disconnected", Servers : [{ ServerId: "{ ClusterId : 1, EndPoint : "****" }", EndPoint: “****”,状态:“断开连接”,类型:“未知”,HeartbeatException:“MongoDB.Driver.MongoConnectionException:打开与服务器的连接时发生异常。---> System.Net.Sockets.SocketException : 无法连接,因为目标机器主动拒绝 ******

最后我们尝试设置不同的超时,但没有任何改变。

var client = new MongoClient(new MongoClientSettings
  { 
    SocketTimeout = TimeSpan.FromSeconds(1),
    MaxConnectionIdleTime = TimeSpan.FromSeconds(1),
    MaxConnectionLifeTime = TimeSpan.FromSeconds(1),
    ConnectTimeout = TimeSpan.FromSeconds(1),
    Servers = url.Servers
  });

所以问题是我们如何知道我们是否在短时间间隔〜(1-2)秒内连接到mongo?

[更新]

我们目前的解决方案是:

private IMongoDatabase Connect(string connectionString, TimeSpan timeout)
{
  var url = MongoUrl.Create(connectionString);
  var client = new MongoClient(url);
  var db = client.GetDatabase(url.DatabaseName);
  var pingTask = db.RunCommandAsync<BsonDocument>(new BsonDocument("ping", 1));
  pingTask.Wait(timeout);
  if (pingTask.IsCompleted)
    log.InfoFormat("Connected to: {0}.", connectionString);
  else
    throw new TimeoutException(string.Format("Failed to connect to: {0}.", connectionString));

  return db;
}

用法

database = Connect(connectionString, TimeSpan.FromSeconds(1));
4

2 回答 2

3

这个问题有下一个解决方法:

var client = new MongoClient(new MongoClientSettings
{
       Server = new MongoServerAddress("xxxx"),
       ClusterConfigurator = builder =>
       {
             builder.ConfigureCluster(settings => settings.With(serverSelectionTimeout: TimeSpan.FromSeconds(10)));
       }
});
于 2015-06-11T00:46:39.640 回答
0

使用新的 API:

         try
            {
                MongoClient client = new MongoClient("xxx"); 
                // if you're running localhost let the parameter empty
                var db = client.GetDatabase("dbName");
                var collection = db.GetCollection<BsonDocument>("collectionName");
                var filter1 = Builders<BsonDocument>.Filter.Empty;
                var filter = new BsonDocument();
                var count = 0;
                   using (var cursor = await collection.FindAsync(filter))
                    {
                      while (await cursor.MoveNextAsync())
                       {
                        var batch = cursor.Current;
                        foreach (var document in batch)
                        {
                          count++;
                        }
                       }
                    }
               MessageBox.Show(count.ToString());
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
于 2016-06-21T01:52:04.500 回答