javascript - Node.js - 真正的大流是阻塞的并且是 CPU 密集型的

标签 javascript node.js stream streaming

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

我尝试了几种不同的技巧来缓解这种情况,但现在有点卡住了。这是我最近尝试将流传输到使用 process.nextTick 的 Transform。

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 问题。

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

最佳答案

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

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

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

关于javascript - Node.js - 真正的大流是阻塞的并且是 CPU 密集型的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23502586/

相关文章:

javascript - 从 node.js 调用的 python "json"结果中在字符 8192 处插入的随机逗号

node.js - 如何在nodejs中获取服务器变量?

node.js - "Failed to load resource: the server responded with a status of 404 (Not Found)"+ "Origin … is not allowed by Access-Control-Allow-Origin."

javascript - nodeJS 视频流,当用户断开连接或移动到不同页面时连接不会关闭

c# - 关闭 HttpWebRequest 以释放资源

VB.NET 应用程序卡住且未运行

javascript - 在并行 RequireJS 中下载脚本依赖项

javascript - 如何在两个不同数组中的项目之间建立链接?

javascript - 尝试根据所选选项显示字段

javascript - 我可以使用 div :before as an anchor to toggle visibility of the rest of the div? 的内容吗