NEXT.JS项目中Axios Cache Interceptor的缓存重验证方案咨询
实现Axios缓存自动重验证(类似SWR机制)
1. 响应拦截器对比数据触发缓存更新
借助Axios Cache Interceptor的缓存操作API,在响应拦截器里对比接口返回的新数据与现有缓存,数据不一致时主动更新缓存:
import axios from 'axios'; import { setupCache } from 'axios-cache-interceptor'; // 初始化带缓存的Axios实例 const axiosInstance = setupCache(axios.create({ // 你的基础请求配置(如baseURL等) }), { storage: { set: (key, value) => localStorage.setItem(key, JSON.stringify(value)), get: (key) => JSON.parse(localStorage.getItem(key)), remove: (key) => localStorage.removeItem(key) }, ttl: 60 * 60 * 1000 // 60分钟缓存有效期 }); // 添加响应拦截器实现自动重验证 axiosInstance.interceptors.response.use(async (response) => { // 生成当前请求的缓存key const cacheKey = axiosInstance.cache.generateKey(response.config); // 获取现有缓存数据 const cachedData = await axiosInstance.cache.get(cacheKey); // 对比新旧数据(可根据实际数据结构替换为更精准的对比逻辑) if (cachedData && JSON.stringify(cachedData.data) !== JSON.stringify(response.data)) { // 数据更新时重置缓存内容与TTL await axiosInstance.cache.set(cacheKey, { ...cachedData, data: response.data, ttl: 60 * 60 * 1000 }); } return response; }, (error) => { return Promise.reject(error); });
2. 配置stale-while-revalidate策略
开启Axios Cache Interceptor的staleWhileRevalidate配置,实现和SWR一致的“先返回缓存、后台异步验证更新”机制:
const axiosInstance = setupCache(axios.create({ // 你的基础请求配置 }), { storage: { set: (key, value) => localStorage.setItem(key, JSON.stringify(value)), get: (key) => JSON.parse(localStorage.getItem(key)), remove: (key) => localStorage.removeItem(key) }, ttl: 60 * 60 * 1000, staleWhileRevalidate: 60 * 60 * 1000 // 缓存过期后仍可临时使用,同时后台请求验证更新 });
开启后,缓存过期但未超出staleWhileRevalidate时长时,会先返回缓存数据,自动发起后台请求验证;若接口返回新数据,会自动更新缓存,后续请求将获取最新内容。
3. 手动触发重验证(可选)
如果需要在特定场景(如用户主动刷新)触发重验证,可删除对应缓存后重新发起请求:
const revalidateTarget = async (requestConfig) => { const cacheKey = axiosInstance.cache.generateKey(requestConfig); await axiosInstance.cache.remove(cacheKey); // 重新请求将获取最新数据并更新缓存 return axiosInstance(requestConfig); }; // 调用示例:比如点击刷新按钮时触发 // revalidateTarget({ url: '/api/your-target-api' });
注意事项
- 数据对比逻辑建议根据实际接口返回结构调整,避免依赖
JSON.stringify(若数据包含Date等特殊类型或键值顺序不稳定),可使用深度对比工具(如lodash的isEqual)。 - 在Next.js服务端组件中,需注意localStorage仅在客户端可用,服务端需切换为内存存储或其他服务端兼容的存储方案。
内容的提问来源于stack exchange,提问作者Victor Braga
相关产品推荐
相关产品推荐

