简体   繁体   English

Nodejs HTTP服务器处理插入DB的多个请求

[英]Nodejs HTTP server handling multiple requests inserting into DB

I have an http server and every time it gets a post request, it is supposed to insert the data into MongoDB. 我有一个http服务器,每次收到一个post请求,它应该将数据插入MongoDB。 This server is supposed to be constantly running and accepting thousands of request in any given second. 该服务器应该在任何给定的秒内持续运行并接受数千个请求。

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. 我觉得我当前的代码速度不够快,每次收到请求时,它会产生一个新的数据库,从而浪费CPU能力。

My current layout 我目前的布局

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);

I have tried replacing db.open with MongoClient.connect, but that considerably slows down processing and I don't know why. 我尝试用MongoClient.connect替换db.open,但这大大减慢了处理速度,我不知道为什么。 In this case, the older version of MongoDB Native for node js seems to work faster. 在这种情况下,旧版本的MongoDB Native for node js似乎工作得更快。

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. 您将希望转向在启动期间打开由HTTP请求处理程序共享的大型连接池的方法。 To tweak the MongoDB connection pool size to suit whatever scalability needs you have, pass an options parameter to your MongoClient.connect call. 要调整MongoDB连接池大小以满足您的任何可伸缩性需求,请将options参数传递给MongoClient.connect调用。

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);  
    }
);

Not sure if this would be better, but you can encapsulate that server inside the db, therefore persisting the connection: 不确定这是否会更好,但您可以将该服务器封装在db中,从而保持连接:

var db = new Db('test', new Server("111.111.11.111", 27017,{auto_reconnect: false}), {safe: true});  

db.open(function(err, db) {
    var server = http.createServer(function (req, res) {
        //now do stuff thru constant open connection
    });      
    db.close();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM