微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何通过同步互联网连接改进异步节点获取?

如何解决如何通过同步互联网连接改进异步节点获取?

我家里有一个快速同步光纤连接。速度非常适合流和大包。然而,由于连接开销,多个异步节点获取非常慢。我从来没有从我的本地主机中获得超过 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())

})

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。