public class MongodbFactory2: IDisposable where T : class
{
//public string connectionString = "mongodb://10.1.55.172";
public string connectionString = ConfigurationManager.AppSettings["mongodb"];
public string databaseName = "myDatabase";
Mongo mongo;
MongoDatabase mongoDatabase;
public MongoCollection mongoCollection;
public MongodbFactory2()
{
mongo = GetMongo();
mongoDatabase = mongo.GetDatabase(databaseName) as MongoDatabase;
mongoCollection = mongoDatabase.GetCollection() as MongoCollection;
mongo.Connect();
}
public void Dispose()
{
this.mongo.Disconnect();
}
///
/// 配置Mongo,将类T映射到集合
///
private Mongo GetMongo()
{
var config = new MongoConfigurationBuilder();
config.Mapping(mapping =>
{
mapping.DefaultProfile(profile =>
{
profile.SubClassesAre(t => t.IsSubclassOf(typeof(T)));
});
mapping.Map();
});
config.ConnectionString(connectionString);
return new Mongo(config.BuildConfiguration());
}
///
/// Connects to server.
///
///
/// Thrown when connection fails.
public void Connect()
{
_connection.Open();
}
2:再看这句:return new Mongo(config.BuildConfiguration());
///
/// Initializes a new instance of the class.
///
/// The mongo configuration.
public Mongo(MongoConfiguration configuration){
if(configuration == null)
throw new ArgumentNullException("configuration");
configuration.ValidateAndSeal();
_configuration = configuration;
_connection = ConnectionFactoryFactory.GetConnection(configuration.ConnectionString);
}
上面代码的最后一句有_connection的生成过程。
3:可以跟踪到最终生成connection的函数,终于看到builder.Pooled这个参数了,这的值就是连接串中的参数。
///
/// Creates the factory.
///
/// The connection string.
///
private static IConnectionFactory CreateFactory(string connectionString){
var builder = new MongoConnectionStringBuilder(connectionString);
if(builder.Pooled)
return new PooledConnectionFactory(connectionString);
return new SimpleConnectionFactory(connectionString);
}
4:再看PooledConnectionFactory是如何创建连接的:这的作用就是将可用连接放入连接池中,而最终真正创建连接的函数是CreateRawConnection()
///
/// Ensures the size of the minimal pool.
///
private void EnsureMinimalPoolSize()
{
lock(_syncObject)
while(PoolSize < Builder.MinimumPoolSize)
_freeConnections.Enqueue(CreateRawConnection());
}
5:真正远程连接部分。
View Code
///
/// Creates the raw connection.
///
///
protected RawConnection CreateRawConnection()
{
var endPoint = GetNextEndPoint();
try
{
return new RawConnection(endPoint, Builder.ConnectionTimeout);
}catch(SocketException exception){
throw new MongoConnectionException("Failed to connect to server " + endPoint, ConnectionString, endPoint, exception);
}
}
private readonly TcpClient _client = new TcpClient();
private readonly List _authenticatedDatabases = new List();
private bool _isDisposed;
///
/// Initializes a new instance of the class.
///
/// The end point.
/// The connection timeout.
public RawConnection(MongoServerEndPoint endPoint,TimeSpan connectionTimeout)
{
if(endPoint == null)
throw new ArgumentNullException("endPoint");
EndPoint = endPoint;
CreationTime = DateTime.UtcNow;