简体   繁体   English

如何在C#MongoDB驱动程序v2.0中获取连接状态?

[英]How to get connection status in the C# MongoDB driver v2.0?

We are starting using new MongoDB driver v2 and we can't understand whether we are connected to the db or not. 我们开始使用新的MongoDB驱动程序v2 ,我们无法理解我们是否连接到数据库。

Our repository code: 我们的存储库代码

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

Where wrong-host and wrong-port are invalid values. wrong-hostwrong-port是无效值。

First we thought that exception will be raised if no one is listening on specified address but driver doesn't throws. 首先,我们认为如果没有人正在监听指定的地址但驱动程序没有抛出异常将被引发。

Next step was to invoke method on the db: 下一步是在db上调用方法:

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

Here we have freez for 30 seconds and than exception. 在这里,我们有freez 30秒而不是例外。 It was not suitable for us to wait 30 seconds to get to know connected we are or not. 我们不适合等待30秒来了解我们是否联系。

System.TimeoutException: A timeout occured after 30000ms selecting a server using CompositeServerSelector{ Selectors = ReadPreferenceServerSelector{ ReadPreference = { Mode = Primary, TagSets = [] } }, LatencyLimitingServerSelector{ AllowedLatencyRange = 00:00:00.0150000 } }. System.TimeoutException:使用CompositeServerSelector选择服务器30000ms后发生超时{Selectors = ReadPreferenceServerSelector {ReadPreference = {Mode = Primary,TagSets = []}},LatencyLimitingServerSelector {AllowedLatencyRange = 00:00:00.0150000}}。 Client view of cluster state is { ClusterId : "1", Type : "Unknown", State : "Disconnected", Servers : [{ ServerId: "{ ClusterId : 1, EndPoint : "****" }", EndPoint: "****", State: "Disconnected", Type: "Unknown", HeartbeatException: "MongoDB.Driver.MongoConnectionException: An exception occurred while opening a connection to the server. ---> System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it ****** 集群状态的客户端视图是{ClusterId:“1”,类型:“未知”,状态:“已断开连接”,服务器:[{ServerId:“{ClusterId:1,EndPoint:”****“}”,EndPoint: “****”,状态:“Disconnected”,键入:“Unknown”,HeartbeatException:“MongoDB.Driver.MongoConnectionException:打开与服务器的连接时发生异常.---> System.Net.Sockets.SocketException :无法建立连接,因为目标计算机主动拒绝它******

Finally we tried to set up different timeouts but nothing changed. 最后,我们尝试设置不同的超时但没有任何改变。

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

So the question is how we could know whether we are connected to the mongo or not in short time interval ~(1-2) seconds? 所以问题是如何在短时间间隔〜(1-2)秒内知道我们是否连接到mongo?

[UPD] [UPD]

Our current solution is: 我们目前的解决方案是

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

usage 用法

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

There is next workaround for this issue : 问题有下一个解决方法:

var client = new MongoClient(new MongoClientSettings
{
       Server = new MongoServerAddress("xxxx"),
       ClusterConfigurator = builder =>
       {
             builder.ConfigureCluster(settings => settings.With(serverSelectionTimeout: TimeSpan.FromSeconds(10)));
       }
});

With the new API : 使用新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);
            }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM