You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在NextJS中实现手动缓存?使用lru-cache等库未生效

在Next.js中实现手动姓名缓存的解决方案

问题根源说明

你使用的lru-cache和memory-cache是服务器端内存缓存库,这类缓存存储在Node.js进程中,浏览器开发者工具的Application标签仅能查看浏览器端缓存(如localStorage、sessionStorage),因此看不到相关内容是正常的。另外,如果在客户端组件中直接使用这些库,会因为环境不兼容导致缓存逻辑失效。


方案1:服务器端手动缓存(适用于API路由、Server Components、Server Actions)

这类缓存运行在服务器端,适合存储需要在服务层复用的数据。

示例:用lru-cache实现服务器端缓存

  1. 安装依赖:
npm install lru-cache
  1. 创建API路由app/api/name/route.js:
import { LRUCache } from 'lru-cache';

// 初始化缓存实例,设置最大存储量和过期时间
const cache = new LRUCache({ max: 50, ttl: 60 * 1000 }); // 最多存50条数据,1分钟过期

// 存入缓存的接口
export async function POST(request) {
  const { name } = await request.json();
  cache.set('user-name', name);
  return Response.json({ status: 'success', message: '姓名已存入服务器缓存' });
}

// 读取缓存的接口
export async function GET() {
  const cachedName = cache.get('user-name');
  return Response.json({ name: cachedName || '未找到缓存的姓名' });
}
  1. 在Server Component中调用:
// app/page.js(默认是Server Component)
async function fetchCachedName() {
  const res = await fetch('/api/name', { cache: 'no-store' });
  return res.json();
}

export default async function Home() {
  const { name } = await fetchCachedName();

  return (
    <div>
      <h1>服务器端缓存的姓名:{name}</h1>
      <form 
        action={async (formData) => {
          await fetch('/api/name', {
            method: 'POST',
            body: JSON.stringify({ name: formData.get('name') }),
            headers: { 'Content-Type': 'application/json' }
          });
          window.location.reload();
        }}
      >
        <input type="text" name="name" placeholder="输入姓名" />
        <button type="submit">存入服务器缓存</button>
      </form>
    </div>
  );
}

注意:服务器端内存缓存是进程内存储,多进程部署(如PM2集群)时缓存不共享,服务器重启后缓存会清空。


方案2:客户端手动缓存(可在Application标签查看)

如果需要在浏览器端存储并在DevTools中查看,使用localStorage或sessionStorage即可。

示例:用localStorage实现客户端缓存

创建客户端组件app/components/NameCache.js:

'use client';

import { useState, useEffect } from 'react';

export default function NameCache() {
  const [inputName, setInputName] = useState('');
  const [cachedName, setCachedName] = useState('');

  // 组件加载时读取浏览器缓存
  useEffect(() => {
    const storedName = localStorage.getItem('user-name');
    if (storedName) setCachedName(storedName);
  }, []);

  // 存入浏览器缓存
  const saveToCache = () => {
    if (!inputName) return;
    localStorage.setItem('user-name', inputName);
    setCachedName(inputName);
    setInputName('');
  };

  // 清空缓存
  const clearCache = () => {
    localStorage.removeItem('user-name');
    setCachedName('');
  };

  return (
    <div>
      <h2>浏览器端缓存示例</h2>
      <input
        type="text"
        value={inputName}
        onChange={(e) => setInputName(e.target.value)}
        placeholder="输入姓名"
      />
      <button onClick={saveToCache}>存入浏览器缓存</button>
      <button onClick={clearCache}>清空缓存</button>
      <p>当前缓存的姓名:{cachedName || '无'}</p>
    </div>
  );
}

在页面中引入该组件:

// app/page.js
import NameCache from './components/NameCache';

export default function Home() {
  return (
    <div>
      <NameCache />
    </div>
  );
}

此时打开浏览器DevTools的Application标签,在Local Storage下就能看到user-name的键值对。


常见问题排查

  • lru-cache在客户端组件不生效:这类库是Node.js专属,客户端组件运行在浏览器环境,无法兼容。
  • 服务器端缓存看不到:服务器内存缓存不在浏览器存储范围内,可通过API返回值或服务器日志验证缓存是否生效。
  • 缓存数据丢失:服务器端缓存随进程重启清空;客户端localStorage是持久化存储,除非手动清除或用户删除浏览器数据。

内容的提问来源于stack exchange,提问作者Pushpendra Chandravanshi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 17:15:10