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
}
相关推荐
碎_浪1 天前
给键盘党的英语记忆工具:我做了一款「打字背单词」桌面应用
前端·程序员·ai编程
阿成学长_Cain1 天前
Linux dirs命令详解|Bash目录堆栈管理快速切换目录实战教程
linux·运维·前端·数据库
yqcoder1 天前
httpOnly 是什么,又有什么用?
开发语言·前端·javascript
IT_陈寒1 天前
Java的Stream.parallel()把我CPU跑爆了,这种优化要谨慎
前端·人工智能·后端
小皮虾1 天前
小程序首页性能优化实战:从 4 秒到 1.8 秒
前端·微信小程序
山河木马1 天前
GPU自动处理专题1-裁剪到底在裁什么(裁剪)
前端·webgl·计算机图形学
奔跑的蜗牛ing1 天前
CentOS Nginx 安装与静态文件服务器配置指南
前端·面试·架构
子兮曰1 天前
Bun 重写为 Rust:11天、64个Claude、16.5万美元,一次改变行业认知的激进实验
前端·后端·bun
子兮曰1 天前
Node.js v26.5.0 深度解读:import Text、流式 ReadableStreamTee、以及隐藏的安全加固浪潮
前端·后端·node.js