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 小时前
SpringCloud 服务雪崩、熔断、降级
后端·spring·spring cloud
Jackson__3 小时前
为什么 Agent 越聊越慢?聊聊 Context(上下文)管理
前端·agent·ai编程
KaMeidebaby3 小时前
卡梅德生物技术快报|抗体合成:多肽抗体合成工程化方案:Nsp2 保守肽多抗制备与多维度验证
前端·网络·数据库·人工智能·算法
青禾网络3 小时前
前端做音画匹配这件事,我从"随机塞"到"AI 自动对齐"
前端·github
2601_963771374 小时前
Hardening Enterprise WordPress Sites Against REST API Leaks and Bad Headers
前端·windows·word·php
蓝银草同学4 小时前
Stream 实战:博客列表排序、过滤与分页(AI 辅助学习 Java 8)
java·前端·后端
2601_957190904 小时前
飞行影院安装施工指南:场地、动感系统与影片内容配套
大数据·前端·人工智能
爱折腾的小黑牛4 小时前
简记往来批量录入功能的实现:从文本到结构化数据
前端·算法
YHHLAI5 小时前
Agent 智能体开发实战 · 第六课:MCP 协议 —— 让 Agent 跨进程调用工具
前端·人工智能
SmartBoyW5 小时前
前端死磕:一文彻底搞懂 JS 事件循环 (Event Loop) 与宏微任务
前端·javascript