我如何一次发出 200 个 400k 请求?

How do I make 400k requests 200 at a time?

我有大量请求,我需要同时 运行 或多或少 200 到 600 个所述请求,但不能超过这个数量。目前我正在同时发送 400k 请求,但它占用了我的堆内存,然后跳到它上面——也就是说它使用了数 GB 的内存,而我没有。

我目前正在使用与此类似的循环来处理请求:

["url1", "url2", ...].forEach(async item => {
    Axios(config)
        .then(res => DO STUFF)
        .catch(err => console.log(err);
    await DO_MORE STUFF
});

链接实际上存储在 MongoDB 集合中,我正在使用 Cursor.forEach。

在async函数中,你需要使用await for stop loop until operation performed。 你已经做了但是也循环了return你需要解决以获得正确结果的承诺数组

const urls = ["url1", "url2", ...]
const allPromise = urls.map(async item => {
    try {
    const res =  await Axios(config)
    await DO_MORE STUFF
    } catch(error) {
        console.log({ error })
    }
});
await Promise.all(allPromise)

如果外部函数不是异步函数那么你可以使用.then

所以你必须将你的数组分割成更小的数组,并为每个切片循环并设置超时。

 let urls = ["url1", "url2", ...];
 let reqPerTime = 400; 
 let rampUp = 0 ; 

function loopRecursively (from ) {
   if ( from > urls.length ) { return ;} 

  let arr = urls.slice(from,  from + reqPerTime ); 
  arr.forEach(async item => {
    Axios(config)
     .then(res => DO STUFF)
     .catch(err => console.log(err);
     await DO_MORE STUFF
    });
   rampUp = rampUp + 500; 
   setTimeout ( () => { loopRecursively( from + reqPerTime ) }, rampUp );
  }

  loopRecursively(0);

可以使用游标的nextObject功能。

这是一个使用它的解决方案(未经测试,可能存在语法错误)

let axiosConfigs = [];
async function runAxios() {
  // Do your axios stuff here on axiosConfigs
  // Here is an example :
  await Promise.all(axiosConfigs.map((config) => {
    return Axios(config);
  }))
  // Once finished, clear the axiosConfigs array      
  axiosConfigs = [];
}

function createAxiosConfig(urlRecord) {
 // return here the axios config for this url record        
}

const cursor = db.collection("urls").find({});

while(await cursor.hasNext()) {
  const urlRecord= await cursor.next();
  axiosConfigs.push(createAxiosConfig(urlRecord));
  if(axiosConfigs.length === 200) {
    await runAllAxioses()
  }
}

有了这个,你将有 200 个 axios 请求的批次。并在所有 200 个 axios 查询结束后开始构建下一批