我认为造成这个问题的可能原因很少:
-
文件描述符限制。
任何打开的连接都使用文件描述符。Linux的默认限制为
file descriptors per process is 1024
。因此,除了分叉node.js进程或增加限制之外,您对此无能为力。除非你有充分的理由,否则不建议使用后者。另一种方法是限制连接的数量,我将在下面介绍。
-
内存堆限制。
这种可能性较小,但仍然是:每个打开的连接都会使用一定量的内存。此外,根据您编写代码和处理可读流的方式,您可能会在可读流中有过多的缓冲,甚至内存泄漏。
限制连接数
以较小的组下载文件,而不是一次全部下载。它可能看起来像这样:
// _.chunk comes from the `lodash` library.
// Now `chunksOfIds` is an array of arrays, each of which contains up to 100 ids.
// i.e [[1,2,...,100],[101,102,...,200],...,[1001,1002,...,1100]]
const chunksOfIds = _.chunk(Ids, 100)
for (const chunk of chunksOfIds) {
const readablePayloadsOfThisChunk: Array<{ filename: string; bugffer: Readable; }> = [];
chunk.map((id) => {
// get key, bucket by id
const buffer = await S3Helper.getReadable({bucket, key} {accessKeyId, secretAccessKey});
readablePayloadsOfThisChunk.push({ filename, buffer });
})
// Note: you have to process your `readablePayloads` here, in the loop,
// so that you will finish your computations before the processing of the next chunk will start
await processReadablePayloads(readablePayloadsOfThisChunk)
}