我们有几个数据库调用可以轻松传输 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/