问题描述
我对MongoDB和NoSQL非常新,我刚刚开始建立一个网站与MongoDB / Norm / ASP.NET MVC 3。
i am very new to MongoDB and NoSQL in general and i've just started building a site with MongoDB / Norm / ASP.NET MVC 3.
我是想知道我应该如何定义连接到我的Mongo数据库。
I am wondering how i should be scoping the connections to my Mongo database.
现在我有一个Basecontroller实例化MongoSession和onActionExecuted我处理它所以我所有的派生控制器将有访问我的MongoSession。 MongoSession类在它的构造函数中打开一个连接,并按照它今天工作的方式将它放在Dispose()上。
Right now i have a Basecontroller that instanciates the MongoSession and onActionExecuted i dispose it so all my deriving controllers will have access to my MongoSession. The MongoSession class opens a connection in its constructor and disposes it on Dispose(), the way it's working today.
private IMongo _mongo;
public MongoSession()
{
_mongo = Mongo.Create("connString");
}
public void Dispose()
{
_mongo.Dispose();
}
我有点担心它可能是持有连接打开太长,如果我
I am a bit worried it might be holding connections open too long if i am doing other stuff aswell in the controllers.
这种方法是否足以保持太多连接打开的风险,或者我应该像下面的示例方法那样做更多的事情?
Is that approach enought to not risking holding too many connections open or should i be doing something more like the example method below?
public void Add<T>(T item) where T : class, new()
{
using (var mongo = Mongo.Create("connString"))
{
mongo.GetCollection<T>().Insert(item);
}
}
另一个后续问题是:
通过Norm昂贵操作打开和关闭MongoDB连接?
Are opening and closing MongoDB connections through Norm "expensive" operations?
推荐答案
保持连接打开,因为重新创建连接是昂贵的。 Mongo是很好的许多连接,开放很长时间。理想情况下,应该做的是与应用程序的所有部分共享连接作为持久连接。 C#驱动程序应该足够聪明,这样做本身,以便它不创建太多的连接,因为它在内部使用连接池,甚至重新使用连接。文档说:与服务器的连接在幕后自动处理(连接池用于提高效率)
I would leave the connection open as re-creating the connection is costly. Mongo is fine with lots of connections, open for a long time. What you ideally should do is to share the connection with all parts of your application as a persistent connection. The C# driver should be clever enough to do this itself, so that it does not create too many connections, as internally it uses "connection pooling" that makes it even re-use connections. The docs say: "The connections to the server are handled automatically behind the scenes (a connection pool is used to increase efficiency)."
干杯,
Derick
cheers,Derick
这篇关于什么时候应该打开和关闭MongoDB连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!