恒美微站
首页
关于我们
建站服务
主题模板
案例展示
资讯中心
联系我们
简单的JS 应用层缓存
首页
资讯中心
/
简单的JS 应用层缓存
简单的JS 应用层缓存
发布时间:2026/10/14 17:14:13
实现前端JS 应用层缓存最简单的思路是用Map做内存缓存用localStorage做持久化再加一个过期时间 TTL。就像手边便签 抽屉笔记本 保质期。简单前端缓存类/** * 简单前端缓存类 * 特点 * 1. 内存 Map读写快页面刷新后消失 * 2. localStorage持久化页面刷新后还在 * 3. TTL给每条缓存设置过期时间 */ class SimpleCache { /** * param {string} prefix 缓存键前缀避免和 localStorage 里其他数据冲突 * param {Storage} storage 存储对象默认 localStorage也可以传 sessionStorage */ constructor(prefix cache:, storage localStorage) { this.prefix prefix; this.storage storage; this.memory new Map(); } /** * 生成真正存到 localStorage 里的 key * 例如 prefixmy-app:keyuser返回 my-app:user */ _key(key) { return this.prefix key; } /** * 写入缓存 * param {string} key 缓存键 * param {*} value 缓存值必须能被 JSON.stringify 序列化 * param {number} ttl 过期时间单位毫秒0 表示永不过期 */ set(key, value, ttl 0) { const record { value, expire: ttl 0 ? Date.now() ttl : 0 }; this.memory.set(key, record); try { this.storage.setItem(this._key(key), JSON.stringify(record)); } catch (e) { console.warn(缓存写入失败, e); } } /** * 读取缓存 * param {string} key * returns {*} 缓存值没找到或已过期返回 undefined */ get(key) { let record this.memory.get(key); if (!record) { const raw this.storage.getItem(this._key(key)); if (!raw) return undefined; try { record JSON.parse(raw); this.memory.set(key, record); } catch (e) { return undefined; } } if (record.expire Date.now() record.expire) { this.remove(key); return undefined; } return record.value; } /** * 判断缓存是否存在且未过期 */ has(key) { return this.get(key) ! undefined; } /** * 删除某个缓存 */ remove(key) { this.memory.delete(key); this.storage.removeItem(this._key(key)); } /** * 清空当前前缀下的所有缓存 */ clear() { this.memory.clear(); for (let i this.storage.length - 1; i 0; i--) { const k this.storage.key(i); if (k k.startsWith(this.prefix)) { this.storage.removeItem(k); } } } }使用示例// 创建一个缓存实例所有 key 都会带 my-app: 前缀 const cache new SimpleCache(my-app:); // 写入缓存有效期 10 秒 cache.set(user, { name: 小明, age: 18 }, 10 * 1000); // 读取缓存 console.log(cache.get(user)); // 输出{ name: 小明, age: 18 } // 10 秒后再读取 setTimeout(() { console.log(cache.get(user)); // 输出undefined因为已经过期并被自动删除 }, 10000);封装请求缓存// 专门给接口请求用的缓存实例 const apiCache new SimpleCache(api:); /** * 带缓存的请求函数 * * param {string} url 请求地址 * param {number} ttl 缓存时间默认 60 秒 * returns {Promiseany} 接口数据 */ async function request(url, ttl 60 * 1000) { // 先尝试读缓存 const cached apiCache.get(url); // 如果缓存存在直接返回不再发请求 if (cached ! undefined) { return cached; } // 缓存没有真正发起网络请求 const res await fetch(url); const data await res.json(); // 请求成功后写入缓存并设置过期时间 apiCache.set(url, data, ttl); // 返回最新数据 return data; }关键点总结内存Map负责快优先从内存读减少localStorage读写次数。localStorage负责持久页面刷新后缓存还在。ttl负责过期避免一直读到旧数据。prefix负责隔离避免不同项目、不同模块的缓存 key 冲突。只适合可序列化数据函数、Map、Set、Date等经过JSON.stringify后可能变形。敏感信息不要放localStorage例如密码、完整 token 要谨慎。