axios请求缓存与重复拦截:“相同请求未完成时,不发起新请求”

javascript 复制代码
import axios from "axios";

// 1. 缓存已完成的请求结果(key:请求URL+参数,value:数据)
const requestCache = new Map();
// 2. 记录正在执行的请求(避免并行重复请求)
const pendingRequests = new Set();

// 请求拦截器:发起请求前检查
axios.interceptors.request.use(config => {
  // 生成请求唯一标识(URL + 方法 + 参数)
  const requestKey = `${config.url}-${config.method}-${JSON.stringify(config.params)}`;

  // 情况1:请求正在执行中,拦截新请求
  if (pendingRequests.has(requestKey)) {
    return Promise.reject(new Error("当前请求已在执行,请勿重复触发"));
  }

  // 情况2:请求已缓存,直接返回缓存数据(不发新请求)
  if (requestCache.has(requestKey)) {
    return Promise.resolve({ data: requestCache.get(requestKey) });
  }

  // 情况3:新请求,加入"正在执行"列表
  pendingRequests.add(requestKey);
  return config;
});

// 响应拦截器:请求完成后更新缓存/状态
axios.interceptors.response.use(
  response => {
    const requestKey = `${response.config.url}-${response.config.method}-${JSON.stringify(response.config.params)}`;
    // 1. 缓存请求结果
    requestCache.set(requestKey, response.data);
    // 2. 从"正在执行"列表移除
    pendingRequests.delete(requestKey);
    return response;
  },
  error => {
    // 错误时也移除"正在执行"状态
    const requestKey = `${error.config.url}-${error.config.method}-${JSON.stringify(error.config.params)}`;
    pendingRequests.delete(requestKey);
    return Promise.reject(error);
  }
);

// 调用示例:相同参数的请求,短时间内只发一次
function fetchStyle() {
  axios.get("/api/page-style", { params: { theme: "light" } })
    .then(res => console.log("样式数据(缓存/新请求):", res.data))
    .catch(err => console.log("请求拦截:", err.message));
}

// 1秒内调用3次,只发1次请求,后2次用缓存
fetchStyle();
setTimeout(fetchStyle, 500);
setTimeout(fetchStyle, 800);

这个地方的set和map使用,为什么不用对象和数组?

  1. 用普通对象 {} 替代 Map:
    可行,但键只能是字符串 / Symbol,且判断键是否存在需要用 obj.hasOwnProperty(key)(不如 map.has(key) 直观)。
  2. 用数组 \[\] 替代 Set:
    可行,但检查是否存在需要 array.includes(key)(O (n) 复杂度,数据量大时效率低),且需要手动去重(if (!array.includes(key)) array.push(key))。
相关推荐
葡萄城技术团队3 小时前
1000 人协同压测的环境瓶颈排查:CPU 争用与 Wi\-Fi
前端
excel5 小时前
Marked 与 Markdown 有什么区别?该怎么选?
前端
步行cgn5 小时前
FormHttpMessageConverter 详解:Spring MVC 中表单数据的读写转换器
java·spring·mvc
Da Da 泓5 小时前
五子棋 Web 端测试用例报告
前端·网络·websocket·网络协议·测试用例·项目
zxcvb1536 小时前
远程查看本地文档:一条轻量 Web 文件服务的工程化链路
前端·远程查看文档
niucloud-admin6 小时前
NIUCLOUD PHP SAAS上门家政使用文档:城市管理
java·前端·php
北岛贰7 小时前
啵啵音乐迎来全新升级!
前端
霸道流氓气质7 小时前
智能客服组件:分层意图识别、RAG Advisor 与人工转接状态机的 Vue3 + Spring AI 生产级实战
java·人工智能·spring
captain3767 小时前
MyBatis操作数据库(入门2)
java·数据库·spring boot·后端·spring·mybatis
步行cgn8 小时前
Spring MVC + Thymeleaf 模板解析失败:从 500 错误到页面正常显示
java·spring·mvc