Performance optimization issue 03 - HTTP request optimization

Small ah lost 2021-09-15 07:36:08
performance optimization issue http request


Chrome Browser request mechanism : The same domain name can only be created at most at the same time 6 individual TCP Connect , In other words, the maximum concurrency of a single domain name is 6

If concurrent requests reach a certain level , Accumulating countless call stacks may lead to memory overflow

Concurrent request

  • Use scenarios

    Send all requests at once , Then wait to receive all the results

    It is suitable for the situation that the number of requests is fixed and asynchronous tasks do not need to be executed in the expected order

  • Promise.all Method

    (async () => {
    const [data1, data2, data3] = await Promise.all([
    Promise.resolve(1),
    Promise.resolve(2),
    Promise.resolve(3),
    ])
    .catch(e => {
    console.error(e)
    })
    console.log(`Received data: ${data1}`)
    console.log(`Received data: ${data2}`)
    console.log(`Received data: ${data3}`)
    })()
     Copy code 

    If an exception occurs in one of the asynchronous tasks , Then all tasks will be regarded as failed , here Promise Go straight into rejected state

  • Promise.allSettled Method

    (async () => {
    const response = await Promise.allSettled([
    Promise.reject(1),
    Promise.resolve(2),
    Promise.resolve(3),
    ])
    console.log('Received data:', response)
    })()
     Copy code 
    [
    { "status": "rejected", "reason": 1 },
    { "status": "fulfilled", "value": 2 },
    { "status": "fulfilled", "value": 3 },
    ]
     Copy code 

    Whether it's successful or unusual , Will return to the corresponding status , Developers filter the results they want according to the business

Serial request

  • Use scenarios

    Perform asynchronous tasks in the expected order , That is, wait for the last await After execution , Then proceed to the next

    It is suitable for the case where the number of requests is fixed and asynchronous tasks need to be executed in the expected order

  • for-of loop

    (async () => {
    const promises = [Promise.resolve(1), Promise.resolve(2), Promise.resolve(3)]
    for (const [index, promise] of promises.entries()) {
    console.log(`Received data: ${await promise}`)
    }
    console.log('Finished')
    })()
     Copy code 
  • Asynchronous traverser

    (async () => {
    const promises = [Promise.resolve(1), Promise.resolve(2), Promise.resolve(3)]
    try {
    for await (const data of promises) {
    console.log('Received data:', data)
    }
    } catch (e) {
    console.error(e)
    }
    console.log('Finished')
    })()
     Copy code 

Quantifying the number of concurrent requests

  • Optimize the scene

    Fragment upload request of large file ; Request to download files in bulk

  • adopt while The loop implements concurrency

    const invariable = ({ list = [], limit = 3, singleComplete = () => {} }) => {
    return new Promise((resolve, reject) => {
    let completeCount = 0, total = list.length
    limit = total > limit ? limit : total
    while(limit--) {
    const { url, data } = list.shift()
    recursion(url, data)
    }
    })
    }
     Copy code 
  • Control the number of requests through recursion

    const recursion = (url, data) => {
    fetchFileStream(url).then(blob => {
    singleComplete({ data, response: blob })
    completeCount += 1
    if (list.length) {
    const { url, data } = list.shift()
    recursion(url, data)
    } else {
    completeCount === total && resolve(true)
    }
    })
    }
     Copy code 

Looking back

Performance optimization No 01 period - Establish performance knowledge system

Performance optimization No 02 period - DNS Analysis and optimization

版权声明
本文为[Small ah lost]所创,转载请带上原文链接,感谢
https://javamana.com/2021/09/20210909131415427t.html

  1. 国内一线互联网公司面试题汇总,2021年大厂Java岗面试必问,
  2. 啃完吃透保你涨薪5K,熬夜整理小米Java面试题,
  3. 和字节跳动大佬的技术面谈,Redis成神之路电子版教程已问世,
  4. Le terme professionnel le plus complet de l'histoire des micro - services interview 50 questions, Byte Jumping Java post Classic interview vrai problème,
  5. After using mybatisplus, I haven't written SQL for a long time
  6. [springboot2 starts from 0] how to write a springboot application?
  7. Huawei cloud guassdb (for redis) released a new version, and the two core features were officially unveiled
  8. 和字節跳動大佬的技術面談,Redis成神之路電子版教程已問世,
  9. 啃完吃透保你漲薪5K,熬夜整理小米Java面試題,
  10. Avec l'interview technique du gigolo, le tutoriel électronique redis est sorti.
  11. Après avoir mangé, assurez - vous d'augmenter votre salaire de 5K et de rester debout tard pour trier les questions d'entrevue Java de millet.
  12. Résumé des questions d'entrevue pour les entreprises Internet nationales de première ligne, qui doivent être posées lors de l'entrevue d'emploi Java de la grande usine en 2021,
  13. Le tri des crachats de sang, la force de l'équipe Tencent pour créer le tutoriel d'introduction au printemps,
  14. Java and scala concurrency Fundamentals
  15. Analysis of java thread source code based on Hotspot
  16. 國內一線互聯網公司面試題匯總,2021年大廠Java崗面試必問,
  17. Introduction au module de contrôle de Connexion MySQL
  18. 大厂高级测试面试题,Java面试基础技能罗列,
  19. Comprendre l'architecture sous - jacente d'InnoDB en exécutant une instruction
  20. Chargeur de classe 1 Tomcat
  21. 小白也能看懂的dubbo3应用级服务发现详解
  22. SpringBoot异步使用@Async原理及线程池配置
  23. Questions d'entrevue de test avancé de Dachang, liste des compétences de base de l'entrevue Java,
  24. SpringBoot异步使用@Async原理及線程池配置
  25. Springboot utilise asynchrone le principe @ async et la configuration du pool de threads
  26. Détails de la découverte du Service d'application Dubbo 3 que Xiaobai peut également comprendre
  27. Springboot utilise asynchrone le principe @ async et la configuration du pool de threads
  28. 如何强大且优雅的搞定Linux文件系统,算法题 JVM,
  29. 太牛了,阿里P7架构师带你看透maven的来龙去脉,
  30. Oracle central et Oracle décentralisé
  31. java JavaBean
  32. Java wrapper type
  33. Java super keyword
  34. Java static keyword
  35. Java this keyword
  36. Java interface
  37. 太牛了,阿裏P7架構師帶你看透maven的來龍去脈,
  38. C'est génial, l'architecte Ali p7 vous montre à travers Maven.
  39. Comment traiter le système de fichiers Linux avec puissance et élégance, algorithme JVM,
  40. Java + SSM Social Insurance Pension System for Computer Graduation Design
  41. Usage of Java scanner
  42. Java inheritance
  43. Java method review
  44. java JVM
  45. Java Basics
  46. Java file operation object IO stream
  47. Java console reads multi character input and output
  48. Java simple array sorting
  49. In addition to MySQL master-slave, you have another choice, Galera
  50. Configuration standard dockerfile et docker-composer.yml
  51. 字节大神强推千页PDF学习笔记,2021Java开发学习路线,
  52. 字节大牛耗时八个月又一力作,靠这份Java知识点PDF成功跳槽,
  53. 字节大牛教你手撕Java学习,最新大厂程序员进阶宝典,
  54. Comment l'automne est - il beau?Ces 24 ensembles de modèles d'automne et d'hiver sont grands, minces et vieillissants
  55. 字節大牛教你手撕Java學習,最新大廠程序員進階寶典,
  56. 字節大牛耗時八個月又一力作,靠這份Java知識點PDF成功跳槽,
  57. Byte Bull vous apprend à déchiqueter Java à la main, le dernier dictionnaire avancé des programmeurs de grandes usines,
  58. Byte Bull a pris huit mois à travailler dur et a réussi à changer d'emploi avec ce PDF Java Knowledge point.
  59. Byte God Push 1000 pages PDF Learning notes, 2021 Java Development Learning route,
  60. Five minutes to understand MySQL index push down