Node.js - 多轮并行io

时间:2013-06-09 17:15:43

标签: javascript node.js io

我最近在一个node.js聚会上,发表演讲的人说了一句话: “你需要能够执行多轮并行io的生成器。回调不会削减它”

我是node.js的新手,不知道这意味着什么。有人可以解释一下吗?

编辑:正如评论中所述,这是一个更详细的版本:我参加了一次聚会,以了解node.js.观众中有人问演讲者他认为node.js的最大缺点是什么。他说,在node.js获得生成器之前,它不具备多轮并行I / O的良好解决方案。任何大型网络应用都必须这样做。在多轮中并行访问memcache就是一个例子,数据库和第三方API是其他的。任何来自Python,Ruby或Go等语言的人都会支持生成器,线程或微线程,因此很难接受平台可以完全依赖回调。

1 个答案:

答案 0 :(得分:0)

他本可以引用一个序列助手,在下一个回调中运行一个任务就意味着该链将同步运行。

这是我用于将大量数据插入Mongo集合的生成器的示例。这产生了要并行执行的操作序列。通过使用回调方法链接它们来执行一百万次插入在这种情况下不太实用。这就是为什么我使用像下面那样的生成器/序列助手。

var Inserter = function (collection) {
    this.collection = collection;
    this.data = [];
    this.maxThreads = 30;
    this.currentThreads = 0;
    this.batchSize = 1000;
    this.queue = 0;
    this.inserted = 0;
    this.startTime = Date.now();
};

Inserter.prototype.add = function(data) {
    this.data.push(data);
};

Inserter.prototype.insert = function(force) {
    var that = this;
    if (this.data.length >= this.batchSize || force) {
        if (this.currentThreads >= this.maxThreads) {
            this.queue++;
            return;
        }
        this.currentThreads++;
        console.log('Threads: ' + this.currentThreads);
        this.collection.insert(this.data.splice(0, this.batchSize), {safe:true}, function() {
            that.inserted += that.batchSize;
            var currentTime = Date.now();
            var workTime = Math.round((currentTime - that.startTime) / 1000)
            console.log('Speed: ' + that.inserted / workTime + ' per sec');
            that.currentThreads--;
            if (that.queue > 0) {
                that.queue--;
                that.insert();
            }
        });
    }
};