前端网络请求并发控制

简介

以下为各大浏览器并发请求限制的数量(只在同一与域名下有效)

在这里插入图片描述
可以看出主流浏览器请求并发数一般在2-8之间,这就可以解释下为什么把一些静态资源放在CDN上了,就是因为同域下并发请求有限制,这样就会造成请求阻塞,从而在一定程度上降低了页面渲染的速度,当然这只是部分原因哈,其他原因,比如请求头小,加载速度快等,在这里就不展开讲了。
回归正题,接下来,咱们以chrome浏览器为例,看下它的并发请求。

浏览器并发

为了演示效果,我在html同时加载10张图片,html如下

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
      <img src="http://localhost:8001/flx_bx/img/dir-small.png" alt="">
      <img src="http://localhost:8001/flx_bx/img/bsl.png" alt="">
      <img src="http://localhost:8001/flx_bx/img/excel.png" alt="">
      <img src="http://localhost:8001/flx_bx/img/loading.gif" alt="">
      <img src="http://localhost:8001/flx_bx/img/pic.png" alt="">
      <img src="http://localhost:8001/flx_bx/img/video.png" alt="">
      <img src="http://localhost:8001/flx_bx/img/s-loading.gif" alt="">
      <img src="http://localhost:8001/flx_bx/img/dir-small1.png" alt="">
      <img src="http://localhost:8001/flx_bx/img/menu_bgm.jpg" alt="">
      <img src="http://localhost:8001/flx_bx/img/code.png" alt="">
  </body>
</html>

很明显,可以看出这10张图片在同一域下,那么咱们看下浏览器是怎么加载的,如下图所示:
在这里插入图片描述

可以看到,浏览器只建立了6个连接,而其他请求则是pending状态,也就验证了浏览器并发限制是存在的,那么接下来,咱们就实现一个脚本,用于控制请求的并发。

控制并发

中心思想,就是当请求数大于指定的阀值时,将剩余请求存起来,等待有请求请求完毕后,再推出。

      class RequestLimit {
        constructor(options) {
          this.unRequsetFn = [];
          this.limit = options.limit || 2;
          this.requestCount = 0;
        }

        async request(fn) {
          if (this.requestCount >= this.limit) {
            await new Promise((resolve) => this.unRequsetFn.push(resolve));
          }
          return this._handlerReq(fn);
        }

        async _handlerReq(fn) {
          this.requestCount++;
          try {
            return await fn();
          } catch (err) {
            return Promise.reject(err);
          } finally {
            this.requestCount--;
            if (this.unRequsetFn.length) {
              this.unRequsetFn[0]();
              this.unRequsetFn.shift();
            }
          }
        }
      }

这段代码主要就是利用async函数的await特性和Promise状态,如果大于阀值就await,状态为pending,如果有请求执行完毕就推出一个,将状态置为Fulfilled

那么测试下:

      var requestLimit = new RequestLimit({ limit: 3 });
      for (let i = 0; i < 8; i++) {
        requestLimit.request(() =>
          fetch(
            "http://localhost:8001/flx_bx/img/dir-small.png"
          )
        );
      }

效果如下图所示:
在这里插入图片描述

瀑布图可以很明显的看出,请求并发数控制在3个了。

这里贴一个另外的解法,这个是看到一个大佬写的,链接在文章最后~

      class TaskQuene {
        constructor(concurrency) {
          this.concurrency = concurrency;
          this.running = 0;
          this.quene = []; // 任务队列
          this.results = [];
          this.callback = null;
        }
        pushTask(task) {
          this.quene.push(task);
          this.next();
        }
        next() {
          while (this.running < this.concurrency && this.quene.length) {
            const task = this.quene.shift();
            // 捕获请求返回值
            task()
              .then((resolve) => {
                this.results.push({ resolve });
              })
              .catch((reason) => {
                this.results.push({ reason });
              })
              .finally(() => {
                this.running--;
                this.next();
              });
            this.running++;
          }

          // 执行回调函数
          if (typeof callback === "function" && this.running == 0) {
            callback(this.results);
          }
        }
      }

      function sendRequest(urls, max, callback) {
        // 简单的错误处理 urls 非数组抛错
        if (!(urls instanceof Array) || urls.length === 0) {
          throw Error(`urls`);
        }

        // 最大请求数目限制
        if (!(max > 0)) {
          max = urls.length;
        }

        // 定义一个任务队列
        const downloadQueue = new TaskQuene(max);
        downloadQueue.callback = callback;

        urls.forEach((link) => {
          let task = () => {
            return fetch(link);
          };
          downloadQueue.pushTask(task);
        });
      }

参考文献

手动维护 HTTP 请求排队

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值