跳转到内容

JavaScript请求缓存

来自代码酷

JavaScript请求缓存[编辑 | 编辑源代码]

JavaScript请求缓存是一种优化技术,用于存储网络请求的响应数据,避免重复请求相同资源,从而提升应用性能和用户体验。本指南将详细介绍其工作原理、实现方式及实际应用场景。

概述[编辑 | 编辑源代码]

在Web开发中,频繁发起相同的网络请求会导致不必要的带宽消耗和延迟。通过缓存机制,可以将已获取的响应存储在内存或本地存储中,后续请求直接从缓存读取,减少服务器负载并加快响应速度。

缓存适用于以下场景:

  • 静态资源(如CSS、JS、图片)
  • 不常变动的API数据
  • 需要快速访问的只读数据

缓存策略[编辑 | 编辑源代码]

常见的缓存策略包括:

1. 浏览器缓存[编辑 | 编辑源代码]

浏览器通过HTTP头(如`Cache-Control`、`ETag`)自动管理缓存。例如:

Cache-Control: max-age=3600

2. 内存缓存[编辑 | 编辑源代码]

使用JavaScript变量临时存储数据:

const cache = {};

async function fetchData(url) {
  if (cache[url]) return cache[url];
  const response = await fetch(url);
  cache[url] = await response.json();
  return cache[url];
}

3. 本地存储[编辑 | 编辑源代码]

利用`localStorage`长期保存数据:

function getCachedData(key) {
  const cached = localStorage.getItem(key);
  return cached ? JSON.parse(cached) : null;
}

代码示例[编辑 | 编辑源代码]

基础实现[编辑 | 编辑源代码]

class RequestCache {
  constructor() {
    this.cache = new Map();
  }

  async get(url) {
    if (this.cache.has(url)) {
      console.log('From cache:', url);
      return this.cache.get(url);
    }

    const response = await fetch(url);
    const data = await response.json();
    this.cache.set(url, data);
    return data;
  }
}

// 使用示例
const cache = new RequestCache();
cache.get('https://api.example.com/data'); // 首次请求
cache.get('https://api.example.com/data'); // 从缓存读取

带过期时间的缓存[编辑 | 编辑源代码]

class TimedCache {
  constructor(ttl = 60000) {
    this.cache = new Map();
    this.ttl = ttl; // 默认1分钟
  }

  async get(url) {
    const cached = this.cache.get(url);
    if (cached && Date.now() - cached.timestamp < this.ttl) {
      return cached.data;
    }

    const response = await fetch(url);
    const data = await response.json();
    this.cache.set(url, { data, timestamp: Date.now() });
    return data;
  }
}

缓存失效策略[编辑 | 编辑源代码]

通过以下方式维护缓存有效性:

  • 时间过期:设置TTL(Time-To-Live)
  • 手动清除:提供清除方法
  • 版本控制:在URL中添加版本号(如`/api?v=2`)

graph LR A[新请求] --> B{缓存存在?} B -->|是| C[检查有效期] C -->|有效| D[返回缓存] C -->|无效| E[发起新请求] B -->|否| E E --> F[更新缓存]

实际应用案例[编辑 | 编辑源代码]

天气预报应用[编辑 | 编辑源代码]

缓存天气API响应,避免每分钟重复请求:

const weatherCache = new TimedCache(300000); // 5分钟缓存

async function getWeather(city) {
  const url = `https://api.weather.com/${city}`;
  return weatherCache.get(url);
}

电商网站商品列表[编辑 | 编辑源代码]

使用`localStorage`缓存商品分类:

function loadCategories() {
  const cached = localStorage.getItem('categories');
  if (cached) return Promise.resolve(JSON.parse(cached));

  return fetch('/api/categories')
    .then(res => res.json())
    .then(data => {
      localStorage.setItem('categories', JSON.stringify(data));
      return data;
    });
}

数学原理[编辑 | 编辑源代码]

缓存效率可通过缓存命中率衡量: Hit Rate=Number of cache hitsTotal requests×100%

理想情况下,应优化缓存策略使该值接近100%。

高级主题[编辑 | 编辑源代码]

  • Service Worker缓存:离线应用的核心技术
  • CDN缓存:分布式边缘缓存
  • HTTP/2 Server Push:服务器主动推送资源

最佳实践[编辑 | 编辑源代码]

1. 对敏感数据禁用缓存 2. 为动态内容设置较短TTL 3. 实现缓存清除机制 4. 监控缓存命中率

通过合理使用请求缓存,可显著提升Web应用性能,同时降低服务器压力。开发者应根据具体场景选择合适的缓存策略和存储方案。