JavaScript實(shí)現(xiàn)支持過期時(shí)間的數(shù)據(jù)緩存功能
要在 JavaScript 中實(shí)現(xiàn)數(shù)據(jù)緩存功能并支持設(shè)置過期時(shí)間,可以使用 localStorage、sessionStorage 或內(nèi)存對象(如 Map 或普通對象)來存儲數(shù)據(jù),并為每個(gè)緩存項(xiàng)設(shè)置一個(gè)過期時(shí)間。以下是一個(gè)簡單的實(shí)現(xiàn)示例:
JavaScript 實(shí)現(xiàn)支持過期時(shí)間的數(shù)據(jù)緩存功能
1. 使用 localStorage 實(shí)現(xiàn)持久緩存
const Cache = {
/**
* 設(shè)置緩存
* @param {string} key - 緩存鍵
* @param {*} value - 緩存值
* @param {number} ttl - 緩存時(shí)間(毫秒)
*/
set(key, value, ttl) {
const data = {
value,
expiry: ttl ? Date.now() + ttl : null, // 計(jì)算過期時(shí)間
};
localStorage.setItem(key, JSON.stringify(data));
},
/**
* 獲取緩存
* @param {string} key - 緩存鍵
* @returns {*} 緩存值或 null(如果過期或不存在)
*/
get(key) {
const data = localStorage.getItem(key);
if (!data) return null;
try {
const { value, expiry } = JSON.parse(data);
if (expiry && Date.now() > expiry) {
localStorage.removeItem(key); // 過期刪除緩存
return null;
}
return value;
} catch (e) {
console.warn("緩存數(shù)據(jù)解析失敗", e);
return null;
}
},
/**
* 刪除緩存
* @param {string} key - 緩存鍵
*/
remove(key) {
localStorage.removeItem(key);
},
/**
* 清空所有緩存
*/
clear() {
localStorage.clear();
},
};
// 使用示例
Cache.set("username", "Alice", 5000); // 設(shè)置緩存5秒后過期
console.log(Cache.get("username")); // 5秒內(nèi)返回 'Alice'
setTimeout(() => console.log(Cache.get("username")), 6000); // 6秒后返回 null注意事項(xiàng)
localStorage只能存儲字符串,因此要使用JSON.stringify和JSON.parse進(jìn)行序列化和反序列化。localStorage的存儲空間一般有限(大約 5MB)。- 如果是跨頁面使用,請確保在相同的域名下。
2. 使用 sessionStorage 實(shí)現(xiàn)數(shù)據(jù)緩存(適合頁面級臨時(shí)存儲)
sessionStorage 是一種瀏覽器存儲機(jī)制,它的特點(diǎn)是數(shù)據(jù)僅在頁面會話(session)期間有效,頁面關(guān)閉后數(shù)據(jù)會被清除。
const SessionCache = {
/**
* 設(shè)置緩存
* @param {string} key - 緩存鍵
* @param {*} value - 緩存值
* @param {number} ttl - 緩存時(shí)間(毫秒)
*/
set(key, value, ttl) {
const data = {
value,
expiry: ttl ? Date.now() + ttl : null, // 計(jì)算過期時(shí)間
};
sessionStorage.setItem(key, JSON.stringify(data));
},
/**
* 獲取緩存
* @param {string} key - 緩存鍵
* @returns {*} 緩存值或 null(如果過期或不存在)
*/
get(key) {
const data = sessionStorage.getItem(key);
if (!data) return null;
try {
const { value, expiry } = JSON.parse(data);
if (expiry && Date.now() > expiry) {
sessionStorage.removeItem(key); // 緩存已過期,刪除
return null;
}
return value;
} catch (e) {
console.warn("緩存數(shù)據(jù)解析失敗:", e);
return null;
}
},
/**
* 刪除緩存
* @param {string} key - 緩存鍵
*/
remove(key) {
sessionStorage.removeItem(key);
},
/**
* 清空所有緩存
*/
clear() {
sessionStorage.clear();
},
};
// **使用示例**
// 設(shè)置緩存,5秒后過期
SessionCache.set("userToken", "abc123", 5000);
// 獲取緩存
console.log(SessionCache.get("userToken")); // 5秒內(nèi)返回 'abc123'
// 5秒后嘗試獲取緩存
setTimeout(() => {
console.log(SessionCache.get("userToken")); // 返回 null
}, 6000);注意事項(xiàng)
sessionStorage數(shù)據(jù)在頁面關(guān)閉或會話結(jié)束時(shí)自動清除。- 在不同的標(biāo)簽頁中,
sessionStorage是獨(dú)立的(不會共享)。 sessionStorage的存儲空間一般為5MB左右。- 數(shù)據(jù)存儲在
sessionStorage時(shí)必須經(jīng)過JSON.stringify和JSON.parse處理。
3. 使用內(nèi)存對象實(shí)現(xiàn)輕量緩存(適合短期緩存)
class MemoryCache {
constructor() {
this.cache = new Map();
}
/**
* 設(shè)置緩存
* @param {string} key - 緩存鍵
* @param {*} value - 緩存值
* @param {number} ttl - 緩存時(shí)間(毫秒)
*/
set(key, value, ttl) {
const expiry = ttl ? Date.now() + ttl : null;
this.cache.set(key, { value, expiry });
}
/**
* 獲取緩存
* @param {string} key - 緩存鍵
* @returns {*} 緩存值或 null(如果過期或不存在)
*/
get(key) {
const item = this.cache.get(key);
if (!item) return null;
if (item.expiry && Date.now() > item.expiry) {
this.cache.delete(key); // 緩存過期,刪除
return null;
}
return item.value;
}
/**
* 刪除緩存
* @param {string} key - 緩存鍵
*/
remove(key) {
this.cache.delete(key);
}
/**
* 清空所有緩存
*/
clear() {
this.cache.clear();
}
}
// 使用示例
const memCache = new MemoryCache();
memCache.set("token", "abc123", 3000); // 設(shè)置緩存3秒后過期
console.log(memCache.get("token")); // 3秒內(nèi)返回 'abc123'
setTimeout(() => console.log(memCache.get("token")), 4000); // 4秒后返回 null三種方式對比
| 特性 | localStorage | sessionStorage | 內(nèi)存緩存 (Map) |
|---|---|---|---|
| 持久性 | 持久存儲,頁面刷新或關(guān)閉后仍保留 | 頁面會話結(jié)束(即關(guān)閉頁面)時(shí)丟失 | 頁面刷新后丟失 |
| 共享性 | 同一域名下所有頁面共享 | 僅當(dāng)前標(biāo)簽頁可用 | 僅當(dāng)前標(biāo)簽頁可用 |
| 性能 | 讀取稍慢(I/O 操作) | 讀取稍慢(I/O 操作) | 更快(內(nèi)存存?。?/td> |
| 適用場景 | 長期存儲、頁面級數(shù)據(jù) | 臨時(shí)存儲頁面狀態(tài)、會話數(shù)據(jù) | 短期存儲、臨時(shí)數(shù)據(jù) |
| 存儲大小限制 | 約 5MB | 約 5MB | 取決于可用內(nèi)存 |
到此這篇關(guān)于JavaScript實(shí)現(xiàn)支持過期時(shí)間的數(shù)據(jù)緩存功能的文章就介紹到這了,更多相關(guān)JavaScript數(shù)據(jù)緩存內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
es6函數(shù)name屬性功能與用法實(shí)例分析
這篇文章主要介紹了es6函數(shù)name屬性,結(jié)合實(shí)例形式分析了es6函數(shù)name屬性基本原理、功能、用法及操作注意事項(xiàng),需要的朋友可以參考下2020-04-04
webpack4手動搭建Vue開發(fā)環(huán)境實(shí)現(xiàn)todoList項(xiàng)目的方法
這篇文章主要介紹了webpack4手動搭建Vue開發(fā)環(huán)境實(shí)現(xiàn)todoList項(xiàng)目的方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2019-05-05
JS實(shí)現(xiàn)監(jiān)控微信小程序的原理
這篇文章主要介紹了JS實(shí)現(xiàn)監(jiān)控微信小程序的原理,本文通過實(shí)例代碼相結(jié)合的形式給大家介紹的非常詳細(xì),需要的朋友可以參考下2018-06-06
使用firebug進(jìn)行調(diào)試javascript的示例
調(diào)試javascript的方法有很多,在本文為大家介紹下使用firebug是如何做到的,感興趣的朋友可以參考下2013-12-12
js實(shí)現(xiàn)網(wǎng)頁計(jì)算器
這篇文章主要為大家詳細(xì)介紹了js實(shí)現(xiàn)網(wǎng)頁計(jì)算器,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-05-05

