用于MongoDB连接的.NET最佳实践? [英] .NET best practices for MongoDB connections?

查看:85
本文介绍了用于MongoDB连接的.NET最佳实践?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近一直在使用GitHub上的C#驱动程序来玩MongoDB(这非常快).我正在测试的小型单线程控制台应用程序一切正常.我可以在8秒内运行单线程添加1,000,000个文档(是的,百万个).仅当我在for循环范围之外使用连接时,才能获得此性能.换句话说,我将为每个插入打开连接,而不是为每个插入打开连接.显然是人为的.

I've been playing with MongoDB recently (It's AMAZINGLY FAST) using the C# driver on GitHub. Everything is working just fine in my little single threaded console app that I'm testing with. I'm able to add 1,000,000 documents (yes, million) in under 8 seconds running single threaded. I only get this performance if I use the connection outside the scope of a for loop. In other words, I'm keeping the connection open for each insert rather than connecting for each insert. Obviously that's contrived.

我想把它提高一个档次,看看它如何在多线程中工作.我这样做是因为我需要模拟具有多个并发请求的网站.我在15到50个线程之间旋转,在所有情况下仍然总共插入150,000个文档.如果我只是让线程运行,每个线程为每个插入操作创建一个新的连接,性能就会停下来.

I thought I'd crank it up a notch to see how it works with multiple threads. I'm doing this because I need to simulate a website with multiple concurrent requests. I'm spinning up between 15 and 50 threads, still inserting a total of 150,000 documents in all cases. If I just let the threads run, each creating a new connection for each insert operation, the performance grinds to a halt.

显然,我需要找到一种共享,锁定或共享连接的方法.问题就在这里.就连接到MongoDB而言,最佳实践是什么?该连接是否应在应用程序的生命周期内保持打开状态(每次操作打开和关闭TCP连接都存在大量延迟)?

Obviously I need to find a way to share, lock, or pool the connection. Therein lies the question. What's the best practice in terms of connecting to MongoDB? Should the connection be kept open for the life of the app (there is substantial latency opening and closing the TCP connection for each operation)?

有人对MongoDB拥有任何现实世界或生产经验,尤其是基础连接吗?

Does anyone have any real world or production experience with MongoDB, and specifically the underlying connection?

这是我的线程示例,其中使用的静态连接已锁定,无法进行插入操作.请提供建议,以在网络环境中最大化性能和可靠性!

Here is my threading sample using a static connection that's locked for insert operations. Please offer suggestions that would maximize performance and reliability in a web context!

private static Mongo _mongo;

private static void RunMongoThreaded()
{
    _mongo = new Mongo();
    _mongo.Connect();

    var threadFinishEvents = new List<EventWaitHandle>();

    for(var i = 0; i < 50; i++)
    {
        var threadFinish = new EventWaitHandle(false, EventResetMode.ManualReset);
        threadFinishEvents.Add(threadFinish);

        var thread = new Thread(delegate()
            {
                 RunMongoThread();
                 threadFinish.Set();
            });

        thread.Start();
    }

    WaitHandle.WaitAll(threadFinishEvents.ToArray());
    _mongo.Disconnect();
}

private static void RunMongoThread()
{
    for (var i = 0; i < 3000; i++)
    {
        var db = _mongo.getDB("Sample");
        var collection = db.GetCollection("Users");
        var user = GetUser(i);
        var document = new Document();
        document["FirstName"] = user.FirstName;
        document["LastName"] = user.LastName;

        lock (_mongo) // Lock the connection - not ideal for threading, but safe and seemingly fast
        {
            collection.Insert(document);
        }
    }
}

推荐答案

此处的大多数答案已经过时了,由于.net驱动程序已经成熟并且添加了无数功能,因此不再适用.

Most answers here are outdated and are no longer applicable as the .net driver has matured and had numberless features added.

查看此处提供的新2.0驱动程序的文档: http://mongodb.github.io/mongo-csharp-driver/2.0/reference /driver/connecting/

Looking at the documentation of the new 2.0 driver found here: http://mongodb.github.io/mongo-csharp-driver/2.0/reference/driver/connecting/

.net驱动程序现在是线程安全的,并且可以处理连接池.根据文档

The .net driver is now thread safe and handles connection pooling. According to documentation

建议将MongoClient实例存储为全局变量,既可以作为静态变量,也可以存储在具有单身寿命的IoC容器中.

It is recommended to store a MongoClient instance in a global place, either as a static variable or in an IoC container with a singleton lifetime.

这篇关于用于MongoDB连接的.NET最佳实践?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆