axios请求缓存

目的

避免重复请求,提升运行效率,适用于获取对实时性要求不高的数据。

实现思路

具体实现

js 复制代码
import { getKey } from './createKey'
import axios from 'axios'

const cache = new Map()
const pendingRequests = new Map()

//缓存请求数据 使用请求锁 防止并发 减少重复请求,复用已有的结果,提升响应速度
export const cacheRequestData = function (config, cacheTime = 60000) {
  const key = getKey(config)
  if (!key) {
    // 无效 key,直接请求,不缓存
    return axios(config).then((res) => res.data)
  }

  const cached = cache.get(key)
  if (cached && cached.expireTime > Date.now()) {
    return Promise.resolve(cached.data)
  }

  if (pendingRequests.has(key)) {
    return pendingRequests.get(key)
  }

  const requestPromise = axios(config)
    .then((res) => {
      const expireTime = Date.now() + cacheTime
      cache.set(key, { expireTime, data: res.data })
      return res.data
    })
    .finally(() => {
      pendingRequests.delete(key)
    })

  pendingRequests.set(key, requestPromise)
  return requestPromise
}
相关推荐
名为沙丁鱼的猫72914 小时前
【审计日志组件实践复盘】前端工程化 + 后端DDD架构(AOP切面拦截日志) + MBG
前端·架构
xqqxqxxq14 小时前
AI智能旅游规划系统 - 前端技术笔记
前端·笔记·旅游
陈随易20 小时前
bm2,MoonBit实现的pm2替代品
前端·后端·程序员
a1117761 天前
农业数字孪生大屏网页 html开源
前端·html
圣光SG1 天前
web操作题练习(六)
前端
闪亮的路灯1 天前
威联通QTS使用自带web服务期代理前端(类似nginx)
前端·nginx·威联通
kyriewen1 天前
我用AI写了半年代码——回头看,这5个能力正在退化
前端·javascript·ai编程
IT_陈寒1 天前
Vite静态资源路径这个坑差点让我加班到凌晨
前端·人工智能·后端
掘金酱1 天前
「TRAE Work 实战帮」征文启动!你沉淀的经验,值得被看见!
前端·人工智能·后端
橙子家1 天前
Windows 上同时安装多个 node 版本
前端