NodeJS,MongoDB,Mongoose节省大数据非阻塞

时间:2014-06-13 20:39:51

标签: javascript node.js mongodb express mongoose

我目前正在使用NodeJS,ExpressJS(带EJS),MongoDB和Mongoose开发一个简单的应用程序。以下是我所面临的问题的简要介绍并寻找一些建议

方案

1)在特定事件中,调用使用SOAP的Web服务并提取数据。

2)API一次返回大约数百万行数据

3)使用mongoose

将拉出的数据保存到MongoDB中

代码

数据库模型 - (myModel.js)

var mongoose = require('mongoose')
var Schema = mongoose.Schema

var prodSchema = new Schema({
    rowIndex: {
        type: Number,
    },
    prodId: {
        type: String,
    },
    prodDesc: {
        type: String,
    },
    prodCategory: {
        type: String,
    }
});

module.exports = mongoose.model('Product', prodSchema);

拉动附加到控制器的数据 - (app.js)

/**
 * Module dependencies.
 */

/* Express */
var express = require('express');
var http = require('http');
var path = require('path');
var fs = require('fs');
var bcrypt = require('bcrypt-nodejs');
var moment = require('moment');
var os = require('os');

var config = require('./config');

/* Models */
var Product = require('./models/myModel');

var soap = require('soap');

var app = express();

/// Include the express body parser
app.configure(function () {
    app.use(express.bodyParser());
});

/* all environments */
app.engine('.html', require('ejs').__express);

app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'html');

app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.cookieParser('your secret here'));
app.use(express.session());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

/* DB Connect */
mongoose.connect( 'mongodb://localhost:27017/productDB', function(err){
    if ('development' == app.get('env')) {
        if (err) throw err;
        console.log('Successfully connected to MongoDB globally');
    }
} );

/* Close DB gracefully */
var gracefulExit = function() { 
  mongoose.connection.close(function () {
    console.log('Mongoose default connection with DB is disconnected through app termination');
    process.exit(0);
  });
}

// If the Node process ends, close the Mongoose connection
process.on('SIGINT', gracefulExit).on('SIGTERM', gracefulExit);

/* development only */
if ('development' == app.get('env')) {
    app.use(express.errorHandler());
}

/********************************************************/
/***** GET *****/
/********************************************************/

app.get('/getproducts', getProducts);

/* If GET on http://localhost:3000/getproducts the call the below function to get data from web service */
function getProducts(req, res){
    var post = req.body;
    var url = 'http://www.example.com/?wsdl';
    soap.createClient(url, function(err, client) {
        client.setSecurity(new soap.BasicAuthSecurity(User, Pass));
        client.someMethod(function(err, result) {
            var product = result.DATA.item;
            for(var i=0; i<product.length; i++) {
                var saveData = new Product({
                    rowIndex: product.ROW_INDEX,
                    prodId: product.PROD_ID,
                    prodDesc: product.PROD_DESC,
                    prodCategory: product.PROD_CATEGORY,
                 });
                 saveData.save();
            }           
        });
    });   
}

/* Create Server */
http.createServer(app).listen(app.get('port'), function(){    
    console.log('Express server listening on port ' + app.get('port') + ' in ' + app.get('env') + ' mode');
});

从网络服务返回的数据

[ { ROW_INDEX: '1',
    PROD_ID: 'A1',
    PROD_DESC: 'New product',
    PROD_CATEGORY: 'Clothes' },
  { ROW_INDEX: '2',
    PROD_ID: 'A2',
    PROD_DESC: 'New product 2',
    PROD_CATEGORY: 'Clothes' },
  { ROW_INDEX: '3',
    PROD_ID: 'A3',
    PROD_DESC: 'New product 3',
    PROD_CATEGORY: 'shoes' },
  .
  .
  . millions of rows
]

需要的问题/建议

我面临的问题是,在将所有数据保存到数据库之前,服务器被阻止,没有其他功能,例如为并发用户呈现页面,或者执行保存更多数据。

我正在创建一个视图,该视图也会返回已保存的数据。这些也将是数百万行数据 - 但这次是从MongoDB获取并传递给EJS中的视图。

非常感谢有关优化运行并行流程和计算大量数据的性能的任何帮助/建议。

3 个答案:

答案 0 :(得分:3)

您的保存不是异步的。这条线阻塞了:

saveData.save();

相反,异步保存模型(在保存完成后传递一个函数运行):

function getProducts(req, res){
    var post = req.body;
    var url = 'http://www.example.com/?wsdl';
    soap.createClient(url, function(err, client) {
        client.setSecurity(new soap.BasicAuthSecurity(User, Pass));
        client.someMethod(function(err, result) {
            var product = result.DATA.item;
            for(var i=0; i<product.length; i++) {
                var saveData = new Product({
                    rowIndex: product.ROW_INDEX,
                    prodId: product.PROD_ID,
                    prodDesc: product.PROD_DESC,
                    prodCategory: product.PROD_CATEGORY,
                });
                saveData.save( function (err, data) {
                    // any statements here will run when this row is saved,
                    // but the loop will continue onto the next product without
                    // waiting for the save to finish
                });
            }           
        });
    });   
    res.send("Getting the data! You can browse the site while you wait...");
}

这样,整个循环将立即(几乎)运行,数据将在进入时保存。同时,您的节点进程可以免费提供其他Web请求。

答案 1 :(得分:1)

听起来像数据复制问题,因为您的数据不会在多个节点上复制。我建议检查你的MongoDB是如何设置的。复制将提高服务的可用性,一个节点响应初始请求,并为其他节点留下相同数据的副本,以响应新的读/写。

如果您的所有读取都是百万行读取,则可能需要一些节点。

快速谷歌提出了关于复制的MongoDB教程。开头段落声明&#34;复制提供冗余并提高数据可用性。&#34;

http://docs.mongodb.org/manual/core/replication-introduction/

答案 2 :(得分:0)

您可能想了解如何使用Streams

  1. 创建一个writable stream,在使用某些数据调用_write()时,会在mongodb中插入数据。缓冲数据并小批量插入会更好。

  2. 创建一个transform stream,用于解析xml的块(当它们到达时)到json对象。如果您能在npm上获得现成的流解析器,那么您很幸运。

  3. 以流形式获取SOAP响应(一百万个项目,但仍然是一个响应流),以及管道:soap响应 - &gt;变换 - &gt;写。这可能需要一些工作。

  4. 收听最后一个流的finish和所有流的error,当第一次发出finisherror时,操作结束。拆除管道设置。(unpipe

  5. 此外,Streams可以暂停和恢复,因此您可能希望使用它来控制数据流。

  6. 上述方法不会提高服务器的处理速度,只是有助于保持响应速度。如果要真正扩展,请构建专用xml到数据库流服务的集群。