我有大量请求,需要同时运行或多或少 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。
最佳答案
您可以使用光标的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 查询结束,就开始构建下一批
关于node.js - 如何一次发出 200 个 400k 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57736746/