Nodejs HTTP服务器处理插入DB的多个请求 [英] Nodejs HTTP server handling multiple requests inserting into DB

查看:162
本文介绍了Nodejs HTTP服务器处理插入DB的多个请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个http服务器,每次收到一个post请求时,都应该将数据插入到MongoDB中。该服务器应该在任何给定的秒内持续运行并接受数千个请求。

I have an http server and every time it gets a post request, it is supposed to insert the data into MongoDB. This server is supposed to be constantly running and accepting thousands of request in any given second.

如何最大限度地提高代码的效率和速度?我觉得我当前的代码速度不够快,每次收到请求时都会产生新的数据库,从而浪费CPU能力。

How can I maximize the efficiency and speed of my code? I feel like my current code is not fast enough and furthermore wastes CPU power when it makes a new db every time it receives a request.

我当前的布局

var server = http.createServer(function (req, res) {

     req.on('data', function(chunk) {
          //Receive my data
     });

     req.on('end', function() {
          //JSON parse my data
          var db = new Db('test', new Server("111.111.11.111", 27017,{auto_reconnect: false}), {safe: true});  

          db.open(function(err, db) {
               //Insert data into DB
               db.close();
          });
     });
}); //End Http server
server.listen(8999);

我尝试用MongoClient.connect替换db.open,但这会大大减慢处理速度不知道为什么。在这种情况下,旧版本的MongoDB Native for node js似乎工作得更快。

I have tried replacing db.open with MongoClient.connect, but that considerably slows down processing and I don't know why. In this case, the older version of MongoDB Native for node js seems to work faster.

推荐答案

你想要转移到在启动期间打开由HTTP请求处理程序共享的大型连接池的方法。要调整MongoDB连接池大小以满足您的任何可伸缩性需求,请传递 options 参数 MongoClient.connect 来电。

You'll want to shift to an approach where you open a large pool of connections during startup that are shared by your HTTP request handlers. To tweak the MongoDB connection pool size to suit whatever scalability needs you have, pass an options parameter to your MongoClient.connect call.

var options = {
    server: {
        // The number of pooled connection available to your app.
        poolSize: 100
    }
};

mongodb.MongoClient.connect('mongodb://111.111.11.111/test', options, 
    function(err, db) {
        var server = http.createServer(function (req, res) {
            // Your req.on calls go here, directly using db rather than creating
            // new instances. Don't close db either.
        });
        server.listen(8999);  
    }
);

这篇关于Nodejs HTTP服务器处理插入DB的多个请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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