下面的代码工作,除了什么看起来像一个保持活跃登录在我的MongoDB日志后,我执行代码创建一个数据库,集合和MongoDB内的用户。登录是使用新创建的用户帐户,并且它不会停止,直到我停止运行创建该用户的应用程序服务。如果用户从Mongo中删除,那么日志记录将进入超速状态,用户没有发现错误,并且每天消耗超过32Gb的磁盘空间。我使用最新的Mongo在。net 4.7.2/c#上运行下面的代码。驱动包版本2.16.1。起初,我认为这是垃圾收集问题与我的方法,但后来我设置所有的对象为空,在结束的方法,这仍然没有影响它。是否有一个命令我缺少告诉Mongo驱动程序释放线程到数据库?我很感激你的帮助。
源代码public async Task<IHttpActionResult> MongoCreateAsync(int companyId, string userEmail)
{
string MongoDB = "";
try
{
string databaseName = "Tester" + companyId.ToString();
//Name Validations.
if (!string.IsNullOrEmpty(databaseName))
{
string ErrorString = "";
if (MongoUtility.MongoDatabaseNameValidation(databaseName, ref ErrorString))
{
//********************************************************************************
// Create
//********************************************************************************
var mail = new MailAddress(userEmail);
string username = CryptoUtility.GenerateUserName();
string password = CryptoUtility.GeneratePassword();
//
//Create Catalog Database and User Instance in MongoDB.
//
var connectionString = CryptoUtility.GetDecryptedString(System.Configuration.ConfigurationManager.ConnectionStrings["MongoConnectionString"].ConnectionString);
MongoClient mongoClient = new MongoClient(connectionString);
//Creates the new Catalog database in Mongo.
var db = mongoClient.GetDatabase(databaseName);
//Create User in the new database in Mongo.
var user = new BsonDocument {
{ "createUser", username },
{ "pwd", password },
{
"roles", new BsonArray
{
new BsonDocument { { "role", "dbOwner" }, { "db", databaseName } },
new BsonDocument { { "role", "read" }, { "db", databaseName } },
new BsonDocument { { "role", "readWrite" }, { "db", databaseName } }
}
}
};
await db.RunCommandAsync<BsonDocument>(user);
//Create connection string to the new database using the created user and
//encrypt the connection string for storage in the Catalog table in SQL.
var connectionString2 = $"mongodb://" + username + ":" + password + "@" + CryptoUtility.GetDecryptedString(ConfigurationManager.AppSettings["MongoPath"]) + "/" + databaseName + "?authSource=" + databaseName + "&readPreference=primary&appname=MongoDB%20Compass%20Community&ssl=false";
MongoDB = CryptoUtility.GetEncryptedString(connectionString2);
/// This code adds a new collection to the MongoDB using the created connection string.
var noSqlDataContext = new MongoDataContext(CryptoUtility.GetDecryptedString(MongoDB), databaseName);
string collectionName = $"CreationInfo";
IGenericNoSqlRepository<CreationInfo> _newRepository = new MongoDbGenericRepository<CreationInfo>(noSqlDataContext, collectionName);
CreationInfo datalist = new CreationInfo
{
CatalogName = databaseName,
CatalogDesc = "Initial Creation",
CompanyId = companyId,
CreatedBy = userEmail
};
await _newRepository.SaveAsync(datalist);
noSqlDataContext = null;
db = null;
mongoClient = null;
}
}
}
catch (Exception ex)
{
Trace.TraceError(ex.ToString());
}
return Ok(MongoDB);
}
public class MongoDataContext: IDisposable
{
private bool disposed = false;
public MongoDataContext(string url, string dbName)
{
MongoClientSettings settings = MongoClientSettings.FromUrl(
new MongoUrl(url)
);
settings.MaxConnectionIdleTime = TimeSpan.FromMinutes(1);
settings.MaxConnectionPoolSize = Convert.ToInt16(10000);
settings.MinConnectionPoolSize = Convert.ToInt16(1);
var client = new MongoClient(settings);
MongoDatabase = client.GetDatabase(dbName);
CreateCollections(dbName);
}
public IMongoDatabase MongoDatabase { get; }
protected void CreateCollections(string dbName)
{
var tCollection = MongoDatabase.GetCollection<Record>("LedZepplin");
}
# region IDisposable
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
}
}
this.disposed = true;
}
# endregion
}
}
这是我的MongoDB日志执行代码后的样子。
2022-07-14T21:31:56.032+0000 I NETWORK [listener] connection accepted from <My IP Address>:60645 #1437728 (21 connections now open)
2022-07-14T21:31:56.039+0000 I NETWORK [conn1437728] received client metadata from <My IP Address>:60645 conn1437728: { application: { name: "MongoDB Compass Community" }, driver: { name: "mongo-csharp-driver", version: "2.16.1.0" }, os: { type: "Windows", name: "Microsoft Windows 10.0.22000", architecture: "x86_32", version: "10.0.22000" }, platform: ".NET Framework 4.8.4515.0" }
2022-07-14T21:31:56.163+0000 I ACCESS [conn1437728] Successfully authenticated as principal UserDataStorage152 on DataStorage152
2022-07-14T21:32:56.312+0000 I NETWORK [listener] connection accepted from <My IP Address>:60652 #1437735 (21 connections now open)
2022-07-14T21:32:56.312+0000 I NETWORK [conn1437735] received client metadata from <My IP Address>:60652 conn1437735: { application: { name: "MongoDB Compass Community" }, driver: { name: "mongo-csharp-driver", version: "2.16.1.0" }, os: { type: "Windows", name: "Microsoft Windows 10.0.22000", architecture: "x86_32", version: "10.0.22000" }, platform: ".NET Framework 4.8.4515.0" }
2022-07-14T21:32:56.452+0000 I ACCESS [conn1437735] Successfully authenticated as principal UserDataStorage152 on DataStorage152
2022-07-14T21:33:56.597+0000 I NETWORK [listener] connection accepted from <My IP Address>:60657 #1437742 (21 connections now open)
2022-07-14T21:33:56.603+0000 I NETWORK [conn1437742] received client metadata from <My IP Address>:60657 conn1437742: { application: { name: "MongoDB Compass Community" }, driver: { name: "mongo-csharp-driver", version: "2.16.1.0" }, os: { type: "Windows", name: "Microsoft Windows 10.0.22000", architecture: "x86_32", version: "10.0.22000" }, platform: ".NET Framework 4.8.4515.0" }
2022-07-14T21:33:56.751+0000 I ACCESS [conn1437742] Successfully authenticated as principal UserDataStorage152 on DataStorage152
将MinConnectionPoolSize更改为0将停止无限keep-alive。
settings.MinConnectionPoolSize = Convert.ToInt16(0);