问题描述
我家里有一个快速同步光纤连接。速度非常适合流和大包。然而,由于连接开销,多个异步节点获取非常慢。我从来没有从我的本地主机中获得超过 2 个异步获取。对于连接开销,每两次获取大约需要 1 秒。我需要一分钟多的时间来处理大约 100 次异步提取。
通过我的 4g 手机作为热点,这只需不到 2 秒。
有没有办法为同步互联网连接捆绑获取?
我使用节点 14 运行此测试用例。
const fetch = require('node-fetch')
const promises = []
for(var i = 0; i < 100; i++) {
promises.push(fetch('https://geolytix.github.io/public/geolytix.svg'))
}
console.time('promise all')
Promise
.all(promises)
.then(arr => {
console.log(arr.length)
console.timeEnd('promise all')
})
.catch(error => {
console.error(error)
})
10 次获取 4g 需要 0.2 秒,100 次需要 1 秒。
在我的千兆线路上,10 个获取请求需要 4 秒,100 个需要 50 秒。
使用 axios.get() 的行为完全相同。
解决方法
我能够通过使用自定义用户代理进行节点获取来解决此问题。自定义用户代理保持活动状态并有 1 个 maxSockets。增加 maxSockets 会影响同步互联网连接的性能。
const https = require('https');
const httpsAgent = new https.Agent({
keepAlive: true,maxSockets: 1
})
const options = {
agent: httpsAgent
}
const getPromise = () => new Promise(resolve=>{
fetch('https://geolytix.github.io/public/geolytix.svg',options)
.then(response => response.text())
//.then(text => console.log(text))
.then(() => resolve())
})