MogoDB驱动源码分析(2)

 MongoServer类源码分析

私有变量定义

        #region private static fields
        private static object staticLock = new object();
        private static Dictionary<MongoServerSettings, MongoServer> servers = new Dictionary<MongoServerSettings, MongoServer>();
        #endregion

        #region private fields
        private object serverLock = new object();
        private object requestsLock = new object();
        private MongoServerSettings settings;
        private List<IPEndPoint> endPoints = new List<IPEndPoint>();
        private MongoServerState state = MongoServerState.Disconnected;
        private IEnumerable<MongoServerAddress> replicaSet;
        private Dictionary<MongoDatabaseSettings, MongoDatabase> databases = new Dictionary<MongoDatabaseSettings, MongoDatabase>();
        private MongoConnectionPool primaryConnectionPool;
        private List<MongoConnectionPool> secondaryConnectionPools;
        private int secondaryConnectionPoolIndex; // used to distribute reads across secondaries in round robin fashion
        private int maxDocumentSize = BsonDefaults.MaxDocumentSize; // will get overridden if server advertises different maxDocumentSize
        private int maxMessageLength = MongoDefaults.MaxMessageLength; // will get overridden if server advertises different maxMessageLength
        private Dictionary<int, Request> requests = new Dictionary<int, Request>(); // tracks threads that have called RequestStart
        private IndexCache indexCache = new IndexCache();
        #endregion


创建一个MongoServer对象的实例,采用了工厂模式和线程安全的单例模式。提供了多种重载方法,默认连接为本机。

#region constructors
/// <summary>
/// Creates a new instance of MongoServer. Normally you will use one of the Create methods instead
/// of the constructor to create instances of this class.
/// </summary>
/// <param name="settings">The settings for this instance of MongoServer.</param>
public MongoServer(
MongoServerSettings settings
) {
this.settings = settings.Freeze();

foreach (var address in settings.Servers) {
endPoints.Add(address.ToIPEndPoint(settings.AddressFamily));
}
}
#endregion

#region factory methods
/// <summary>
/// Creates a new instance or returns an existing instance of MongoServer. Only one instance
/// is created for each combination of server settings.
/// </summary>
/// <returns>
/// A new or existing instance of MongoServer.
/// </returns>
public static MongoServer Create() {
return Create("mongodb://localhost");
}

/// <summary>
/// Creates a new instance or returns an existing instance of MongoServer. Only one instance
/// is created for each combination of server settings.
/// </summary>
/// <param name="builder">Server settings in the form of a MongoConnectionStringBuilder.</param>
/// <returns>
/// A new or existing instance of MongoServer.
/// </returns>
public static MongoServer Create(
MongoConnectionStringBuilder builder
) {
return Create(builder.ToServerSettings());
}

/// <summary>
/// Creates a new instance or returns an existing instance of MongoServer. Only one instance
/// is created for each combination of server settings.
/// </summary>
/// <param name="settings">Server settings.</param>
/// <returns>
/// A new or existing instance of MongoServer.
/// </returns>
public static MongoServer Create(
MongoServerSettings settings
) {
lock (staticLock) {
MongoServer server;
if (!servers.TryGetValue(settings, out server)) {
server
= new MongoServer(settings);
servers.Add(settings, server);
}
return server;
}
}

/// <summary>
/// Creates a new instance or returns an existing instance of MongoServer. Only one instance
/// is created for each combination of server settings.
/// </summary>
/// <param name="url">Server settings in the form of a MongoUrl.</param>
/// <returns>
/// A new or existing instance of MongoServer.
/// </returns>
public static MongoServer Create(
MongoUrl url
) {
return Create(url.ToServerSettings());
}

/// <summary>
/// Creates a new instance or returns an existing instance of MongoServer. Only one instance
/// is created for each combination of server settings.
/// </summary>
/// <param name="connectionString">Server settings in the form of a connection string.</param>
/// <returns>
/// A new or existing instance of MongoServer.
/// </returns>
public static MongoServer Create(
string connectionString
) {
if (connectionString.StartsWith("mongodb://")) {
var url
= MongoUrl.Create(connectionString);
return Create(url);
}
else {
var builder
= new MongoConnectionStringBuilder(connectionString);
return Create(builder);
}
}

/// <summary>
/// Creates a new instance or returns an existing instance of MongoServer. Only one instance
/// is created for each combination of server settings.
/// </summary>
/// <param name="uri">Server settings in the form of a Uri.</param>
/// <returns>
/// A new or existing instance of MongoServer.
/// </returns>
public static MongoServer Create(
Uri uri
) {
var url
= MongoUrl.Create(uri.ToString());
return Create(url);
}
#endregion

公开的属性

        #region public properties
        /// <summary>
        /// Gets the admin database for this server.
        /// </summary>
        public virtual MongoDatabase AdminDatabase {
            get { return GetDatabase("admin"); }
        }

        /// <summary>
        /// Gets the connection pool (if connected to a replica set this is the connection pool to the primary).
        /// </summary>
        public virtual MongoConnectionPool ConnectionPool {
            get { return primaryConnectionPool; }
        }

        /// <summary>
        /// Gets the IP end points for this server.
        /// </summary>
        public virtual IEnumerable<IPEndPoint> EndPoints {
            get { return endPoints; }
        }

        /// <summary>
        /// Gets the index cache (used by EnsureIndex) for this server.
        /// </summary>
        public virtual IndexCache IndexCache {
            get { return indexCache; }
        }

        /// <summary>
        /// Gets the max document size for this server (not valid until connected).
        /// </summary>
        public virtual int MaxDocumentSize {
            get { return maxDocumentSize; }
        }

        /// <summary>
        /// Gets the max message length for this server (not valid until connected).
        /// </summary>
        public virtual int MaxMessageLength {
            get { return maxMessageLength; }
        }

        /// <summary>
        /// Gets a list of the members of the replica set (not valid until connected).
        /// </summary>
        public virtual IEnumerable<MongoServerAddress> ReplicaSet {
            get { return replicaSet; }
        }

        /// <summary>
        /// Gets the RequestStart nesting level for the current thread.
        /// </summary>
        public virtual int RequestNestingLevel {
            get {
                int threadId = Thread.CurrentThread.ManagedThreadId;
                lock (requestsLock) {
                    Request request;
                    if (requests.TryGetValue(threadId, out request)) {
                        return request.NestingLevel;
                    } else {
                        return 0;
                    }
                }
            }
        }

        /// <summary>
        /// Gets a read only list of the connection pools to the secondary servers (when connected to a replica set).
        /// </summary>
        public IList<MongoConnectionPool> SecondaryConnectionPools {
            get { return secondaryConnectionPools.AsReadOnly(); }
        }

        /// <summary>
        /// Gets the settings for this server.
        /// </summary>
        public virtual MongoServerSettings Settings {
            get { return settings; }
        }

        /// <summary>
        /// Gets the current state of this server (as of the last operation, not updated until another operation is performed).
        /// </summary>
        public virtual MongoServerState State {
            get { return state; }
        }
        #endregion

未完待续

原文地址:https://www.cnblogs.com/lirenqing/p/2009585.html