本文目录导读:

是的,脚本可以通过多种方式自动缓存API响应,以下是实现方法和最佳实践:
内存缓存(最简单)
// 简单内存缓存实现
class APICache {
constructor(ttl = 60000) { // 默认缓存1分钟
this.cache = new Map();
this.ttl = ttl;
}
async get(key, fetchFn) {
const cached = this.cache.get(key);
if (cached && Date.now() - cached.timestamp < this.ttl) {
return cached.data;
}
const data = await fetchFn();
this.cache.set(key, { data, timestamp: Date.now() });
return data;
}
}
// 使用示例
const cache = new APICache(30000); // 30秒缓存
const response = await cache.get('users', () => fetch('/api/users'));
LocalStorage/IndexedDB(持久化)
// LocalStorage缓存
class PersistentCache {
constructor(prefix = 'api_cache_') {
this.prefix = prefix;
}
async get(key, fetchFn, ttl = 3600000) {
const cacheKey = this.prefix + key;
const cached = localStorage.getItem(cacheKey);
if (cached) {
const { data, timestamp } = JSON.parse(cached);
if (Date.now() - timestamp < ttl) {
return data;
}
}
const data = await fetchFn();
localStorage.setItem(cacheKey, JSON.stringify({
data,
timestamp: Date.now()
}));
return data;
}
}
使用Service Worker(高级方案)
// service-worker.js
self.addEventListener('fetch', (event) => {
if (event.request.url.includes('/api/')) {
event.respondWith(
caches.match(event.request)
.then(cachedResponse => {
if (cachedResponse) return cachedResponse;
return fetch(event.request).then(response => {
const clonedResponse = response.clone();
caches.open('api-cache-v1')
.then(cache => {
cache.put(event.request, clonedResponse);
});
return response;
});
})
);
}
});
使用第三方库
axios-cache-adapter
import axios from 'axios';
import { setupCache } from 'axios-cache-adapter';
const cache = setupCache({
maxAge: 15 * 60 * 1000, // 15分钟
exclude: { query: false }
});
const api = axios.create({
adapter: cache.adapter
});
const response = await api.get('/api/users');
react-query (前端框架)
import { useQuery } from 'react-query';
const { data } = useQuery('users', () => fetch('/api/users'), {
staleTime: 5 * 60 * 1000, // 5分钟内不重新请求
cacheTime: 30 * 60 * 1000 // 30分钟内保留缓存
});
缓存策略建议
// 智能缓存策略
class SmartCache {
constructor() {
this.cache = new Map();
this.strategies = {
'long': 3600000, // 1小时(很少变化的数据)
'medium': 300000, // 5分钟(常规数据)
'short': 30000, // 30秒(频繁变化的数据)
'no-cache': 0 // 不缓存(实时数据)
};
}
async fetchWithStrategy(url, strategy = 'medium') {
const ttl = this.strategies[strategy];
if (ttl === 0) return fetch(url).then(res => res.json());
const cached = this.cache.get(url);
if (cached && Date.now() - cached.timestamp < ttl) {
console.log('返回缓存数据');
return cached.data;
}
const data = await fetch(url).then(res => res.json());
this.cache.set(url, { data, timestamp: Date.now() });
return data;
}
}
注意事项
- 缓存失效策略:合理设置TTL,避免返回过期数据
- 内存管理:限制缓存大小,定期清理
- 错误处理:缓存失败时回退到实时请求
- 敏感数据:避免缓存包含认证信息的数据
- 条件请求:使用ETag/Last-Modified等HTTP缓存头
生产环境选择建议
| 场景 | 推荐方案 |
|---|---|
| 简单脚本 | 内存缓存 |
| 需要持久化 | LocalStorage |
| 大量数据 | IndexedDB |
| 前端应用 | react-query/SWR |
| 服务端 | Redis/Memcached |
| 离线支持 | Service Worker |
缓存能显著提升性能,但需要根据业务场景选择合适的策略,建议先从简单的内存缓存开始,逐步增加复杂度。