node.js - 如何通过同步互联网连接改进异步节点获取?
问题描述
我家里有一个快速的同步光纤连接。速度非常适合流和大型包裹。然而,由于连接开销,多个异步节点获取非常慢。我从本地主机获取的异步数据从未超过 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())
})
推荐阅读
- php - 使用
- windows-10 - Minecraft Bedrock(WIN10) world corrupted because of missing db/MANIFEST file
- python - Match the values in dict
- python - how to add numbers coming from an output created by a file
- python - python: how to access values in nested dictionaries using loops
- android - Is it possible to playback some text using Google Assistant?
- google-sheets - google sheets - is it possible to match only the "duplicate values" from a column?
- regex - 如何使用正则表达式来完成以下任务?
- php - filesize(): 使用 twitter api 发布视频时统计失败 | PHP
- python - 时间序列 - 识别方波类型信号的方法