解决重复请求

  • 时间:2021-03-20 21:21 作者:CBDxin 来源: 阅读:838
  • 扫一扫,手机访问
摘要:在我们的日常开发当中,很多时候会出现短时间内接口重复请求的情况,假如没有妥当地解决,很可能会造成以下的影响:对于get请求:页面触发屡次渲染,造成页面抖动的现象;各个请求受网络等因素的影响,响应返回的时间无法确定,导致响应返回顺序与请求顺序不一致,也就是竟态问题。如下图所示,期待的回调函数的执行顺序

在我们的日常开发当中,很多时候会出现短时间内接口重复请求的情况,假如没有妥当地解决,很可能会造成以下的影响:

对于get请求:
  1. 页面触发屡次渲染,造成页面抖动的现象;
  2. 各个请求受网络等因素的影响,响应返回的时间无法确定,导致响应返回顺序与请求顺序不一致,也就是竟态问题。如下图所示,期待的回调函数的执行顺序应是回调1 > 回调2 > 回调3,但实际顺序是回调2 > 回调3 > 回调1;


    image.png
  3. 增大服务器压力;
对于post请求:
  1. 服务端生成屡次记录;
  2. 产生竟态,导致数据絮乱;

处理方案

  1. 节流

以肯定的频率发送请求,即在特定时间内只允许发送一次请求:

throttle(time, function() { // todo})

适用于频繁触发并且需要给予客户少量反馈的场景,如:resize、scroll、mousemove

  1. 防抖

间隔时间大于指定时间才发送请求:

debounce(time, function() {  // todo})
  1. 按序请求
    顾名思义,就是按照开发者期待的顺序,将各个请求存储在一个队列当中,只有当上一个请求的数据响应了,才能继续发起下一次请求。


    image.png
  1. 同时存在多个请求时,只取最新请求数据
    当触发新的请求时,取消正在pending中的请求,使得永远只有最新的请求可以最终生效。


    image.png

方案1,2 时间间隔不好把控,并且由于会丢失掉部分请求,因而只能针对get请求;
方案3看起来最笨,等待时间长,请求未减少,但由于他将请求排成了一个队列,所以可以避免post请求导致数据数据絮乱的情况;
方案4的请求未减少,并且实际上也无法控制该请求能否已经到达服务器,但该方案保证了在前台不执行无效的响应回调;

根据项目的实际情况,我最终选择了方案4,而该方案恰好可以通过axios的 cancelToken来实现。

实现思路

设置一个列表pendingList,用于存储当前处于pending的请求,在每个请求发送之前,先判断当前请求能否已经存在于pendingList中。若存在,则说明该请求已被请求过,造成了重复请求,这时候则需要把重复的请求cancel,再把新请求增加到pendingList中。若不存在,则说明这个请求是干净的,可进行正常请求,同时也需要把这个请求增加到pendingList中,在请求结束后再把该请求从pendingList中移除。

其中,我们可以通过axios cancelToken来取消请求

axios cancelToken

axios提供了两种方法来取消请求

  1. 通过axios.CancelToken.source生成取消令牌token和取消方法cancel
const CancelToken = axios.CancelToken;const source = CancelToken.source();axios.get('/user/12345', {  cancelToken: source.token}).catch(function (thrown) {  if (axios.isCancel(thrown)) {    console.log('Request canceled', thrown.message);  } else {    // handle error  }});axios.post('/user/12345', {  name: 'new name'}, {  cancelToken: source.token})// cancel the request (the message parameter is optional)source.cancel('Operation canceled by the user.');
  1. 通过axios.CancelToken构造函数生成取消函数
const CancelToken = axios.CancelToken;let cancel;axios.get('/user/12345', {  cancelToken: new CancelToken(function executor(c) {    // An executor function receives a cancel function as a parameter    cancel = c;  })});// cancel the requestcancel();

实现

设置一个列表pendingList,用于存储当前处于pending的请求

const pendingList = new Map();

提供getFetchKey方法,用于生成各个请求的标识,当为GET请求时,由于只用于获取数据,因而只需当method和url都一致时,我们即可以认为这是同一请求,而其余请求则还需要加上请求的参数。

const getFetchKey = (config) => {  const { useCancelToken } = config;  //useCancelToken 用于配置该接口能否需要检测查复请求  if (useCancelToken) {    const { headers, url, data, method, params } = config;    let token;    if (method === 'GET') {      token = [method, url].join('&');    } else {      token = [method, url, JSON.stringify(data), JSON.stringify(params)].join('&');    }    return token;  }};

增加请求到pendingList

const addPending = (config) => {  const fetchKey = getFetchKey(config);  if (fetchKey) {    config.cancelToken =      config.cancelToken ||      new axios.CancelToken((cancel) => {        if (!pendingList.has(fetchKey)) {          pendingList.set(fetchKey, cancel);        }      });  }};

把请求从pendingList移除

const removePending = (config) => {  const fetchKey = getFetchKey(config);  if (fetchKey) {    if (pendingList.has(fetchKey)) {      pendingList.delete(fetchKey);    }  }};

把请求从pendingList移除并取消该请求

const cancelPending = (config) => {  const fetchKey = getFetchKey(config);  if (fetchKey) {    if (pendingList.has(fetchKey)) {      const cancel = pendingList.get(fetchKey);      cancel(fetchKey);      pendingList.delete(fetchKey);    }  }};

在阻拦器中增加以上方法

axios.interceptors.request.use((config) => {  //发送请求前首先检查该请求能否已经重复,重复则进行取消并移除  cancelPending(config);  //增加该请求到pendingList中  addPending(config);  return config;});axios.interceptors.response.use((response) => {  const config = response.config;  //请求完成后移除该请求  removePending(config);  return response;});

最后,因取消请求抛出的error我们不应该返回给客户,使用axios.isCancel()判断当前请求能否是主动取消的

  axios.(options).then(...)..catch((error) => {        if (axios.isCancel(error)) {          console.warn('repeated request: ' + error.message);          return;        }        reject(error);      });
  • 全部评论(0)
最新发布的资讯信息
【系统环境|】2FA验证器 验证码如何登录(2024-04-01 20:18)
【系统环境|】怎么做才能建设好外贸网站?(2023-12-20 10:05)
【系统环境|数据库】 潮玩宇宙游戏道具收集方法(2023-12-12 16:13)
【系统环境|】遥遥领先!青否数字人直播系统5.0发布,支持真人接管实时驱动!(2023-10-12 17:31)
【系统环境|服务器应用】克隆自己的数字人形象需要几步?(2023-09-20 17:13)
【系统环境|】Tiktok登录教程(2023-02-13 14:17)
【系统环境|】ZORRO佐罗软件安装教程及一键新机使用方法详细简介(2023-02-10 21:56)
【系统环境|】阿里云 centos 云盘扩容命令(2023-01-10 16:35)
【系统环境|】补单系统搭建补单源码搭建(2022-05-18 11:35)
【系统环境|服务器应用】高端显卡再度登上热搜,竟然是因为“断崖式”的降价(2022-04-12 19:47)
手机二维码手机访问领取大礼包
返回顶部