如何在 SSR 期间缓存第三方 API 响应以提高性能?

解读

在 Next.js 的服务器端渲染(SSR)场景中,频繁调用第三方 API 可能导致性能瓶颈。缓存机制的核心目标是减少重复请求和响应处理时间,从而提升应用的响应速度和服务器负载效率。需要结合 Next.js 的特性(如 getServerSideProps、API 路由)和中国国内的网络环境(如 CDN 分布、本地缓存策略)设计合理的缓存方案。

知识点

  1. Next.js 的 SSR 缓存机制:

    • getServerSideProps 中的缓存策略(如使用 node-cache 或 Redis)。
    • HTTP 缓存头(Cache-Control、ETag、Last-Modified)。
    • API 路由的缓存实现(如使用 middleware 或自定义缓存逻辑)。
    • 缓存失效策略(TTL、版本号、时间戳)。
  2. 性能优化公式:

    • 缓存命中率 = (缓存命中请求数) / (总请求数)
    • 总响应时间 = 网络传输时间 + 服务器处理时间(缓存未命中时)
    • 缓存命中后总响应时间 = 网络传输时间 + 缓存读取时间
  3. 中国国内场景适配:

    • 需考虑 CDN 分布式缓存(如阿里云 CDN)。
    • 高并发场景下需结合 Redis 分布式缓存。
    • 需处理跨域请求(CORS)和数据一致性问题。

答案

在 Next.js 的 SSR 场景中,缓存第三方 API 响应可通过以下方式实现:

1. 使用 Node.js 缓存库(如 node-cache)

在 getServerSideProps 中集成缓存中间件,减少重复请求:

// pages/index.js
import { cache } from 'node-cache';

const apiCache = new cache({ stdTTL: 600 }); // 缓存 10 分钟

export async function getServerSideProps(context) {
  const { req } = context;
  const cacheKey = `third-party-api:${req.url}`;
  
  // 检查缓存是否存在
  if (apiCache.has(cacheKey)) {
    return {
      props: { data: apiCache.get(cacheKey) }, // 直接返回缓存数据
    };
  }
  
  // 未命中缓存时调用第三方 API
  const res = await fetch('https://api.example.com/data');
  const data = await res.json();
  
  // 存储缓存数据
  apiCache.set(cacheKey, data);
  
  return {
    props: { data },
  };
}

2. 通过 HTTP 缓存头控制缓存

在第三方 API 响应中设置 Cache-Control 和 ETag,利用浏览器或 CDN 缓存:

// pages/api/cache.js
export default async function handler(req, res) {
  const cacheKey = `third-party-api:${req.query.endpoint}`;
  const cachedResponse = await fetch('https://api.example.com/data', {
    headers: {
      'Cache-Control': 'public, max-age=3600', // 设置缓存时间
    },
  });
  
  const data = await cachedResponse.json();
  res.setHeader('Cache-Control', 'public, max-age=3600'); // 传递缓存策略
  res.status(200).json(data);
}

3. 结合 API 路由实现动态缓存

在 Next.js API 路由中封装缓存逻辑,支持按需更新:

// pages/api/third-party.js
import { cache } from 'node-cache';

const apiCache = new cache({ stdTTL: 600 }); // 缓存 10 分钟

export default async function handler(req, res) {
  const { query } = req;
  const cacheKey = `third-party-api:${query.endpoint}`;
  
  // 检查缓存是否存在
  if (apiCache.has(cacheKey)) {
    return res.status(200).json(apiCache.get(cacheKey));
  }
  
  // 未命中缓存时调用第三方 API
  const response = await fetch(`https://api.example.com/${query.endpoint}`);
  const data = await response.json();
  
  // 存储缓存数据
  apiCache.set(cacheKey, data);
  
  return res.status(200).json(data);
}

4. 缓存失效策略

  • 时间戳控制:
    const cacheKey = `third-party-api:${endpoint}`;
    const cachedData = apiCache.get(cacheKey);
    if (cachedData && Date.now() - cachedData.timestamp < 3600000) {
      return { props: { data: cachedData.value } };
    }
    
  • 版本号控制:
    const cacheKey = `third-party-api:${endpoint}:${version}`;
    

拓展思考

  1. 缓存与 ISR 的协同:
    在静态站点生成(SSG)场景中,可结合 ISR 的增量更新能力,将高频数据缓存到服务器端,低频数据通过 ISR 生成。例如,使用 getStaticProps 配合 revalidate 参数:

    export async function getStaticProps() {
      const data = await fetch('https://api.example.com/data');
      return { props: { data }, revalidate: 60 }; // 每 60 秒刷新
    }
    
  2. 分布式缓存的适配:
    在高并发场景下,需使用 Redis 等分布式缓存系统,避免单机缓存的性能瓶颈。例如,通过 ioredis 实现:

    const Redis = require('ioredis');
    const redis = new Redis({ host: 'localhost', port: 6379 });
    
    async function getCache(key) {
      const cached = await redis.get(key);
      if (cached) return JSON.parse(cached);
      return null;
    }
    
    async function setCache(key, value, ttl) {
      await redis.setex(key, ttl, JSON.stringify(value));
    }
    
  3. 缓存穿透与雪崩的防范:

    • 缓存穿透:对空数据设置默认值(如 null)。
    • 缓存雪崩:使用不同的 TTL 策略,或引入随机延迟(如 stdTTL: 600 + Math.random() * 60)。
  4. CDN 缓存优化:
    在中国国内部署时,可结合阿里云 CDN 的缓存规则,对第三方 API 的静态响应(如 JSON 数据)设置缓存时间,减少回源压力。例如,通过 CDN 的 Cache-Control 配置:

    Cache-Control: public, max-age=86400, s-maxage=3600
    

    其中 s-maxage 控制 CDN 缓存时间,max-age 控制浏览器缓存时间,两者协同可降低服务器负载。

  5. 性能监控与调优:
    通过 next.config.js 配置 experimental: { isr: true } 启用 ISR,同时使用 next.js 的 swr 库(客户端)或 axios(服务端)的缓存插件进行监控,确保缓存策略符合业务需求。