【问题标题】:Node.js - Really large streams are blocking and CPU intensiveNode.js - 真正的大流是阻塞和 CPU 密集型的
【发布时间】:2014-06-23 12:46:36
【问题描述】:

我们有一些数据库调用可以轻松流式传输 10 万条记录。我们遇到的问题是,每当我们使用这些流之一时,它都会与 CPU 挂钩,并且似乎会阻塞所有其他进程。

我尝试了一些不同的技巧来缓解这种情况,但现在有点卡住了。这是我最近尝试将流通过管道传输到使用 process.nextTick 的转换。

var stream = require('stream');
var util   = require('util');

function StreamThrottler() {
  stream.Transform.call(this, { objectMode: true });
}

util.inherits(StreamThrottler, stream.Transform);

StreamThrottler.prototype._transform = function(chunk, encoding, cb) {

  process.nextTick(function() {
      console.log('chunk');
      // note: I'm intentionally not pushing the chunk 
      // onto the stream for testing
      cb();
  });
};

StreamThrottler.prototype._flush = function(cb) {
  cb();
};

var streamThrottler = new StreamThrottler();

// now the db call
this.largeDatabaseResultStream().pipe(streamThrottler);

我注意到this Node.js 问题可能相关也可能不相关。

有人对如何解决这个问题有任何其他想法吗?

【问题讨论】:

标签: javascript node.js stream streaming


【解决方案1】:

当您使用objectMode: true 时,本机流实现可能必须缓冲和序列化数据。

所以使用节流器流的想法是一个好主意,所以也许这个流会使用objectMode: false,而在下游,你可以使用方便的objectMode: true

请注意,混合不同类型的流可能会给您带来一些错误。
{objectMode: false} ==> {objectMode: true} 可以(缓冲区只是另一种对象)
{objectMode: true} ==> {objectMode: false} 不行(除非数据本身就是缓冲区)

【讨论】:

  • 看看 promises 和 generator 的 next 方法。它们可能会派上用场。
猜你喜欢
  • 2011-03-30
  • 1970-01-01
  • 2013-03-27
  • 2011-08-08
  • 2016-06-23
  • 2023-03-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多