代码拉取完成,页面将自动刷新
const cache = Symbol('cache');
const SECOND = 1000;
const MINUTE = SECOND * 60;
const HOUR = MINUTE * 60;
const DAY = HOUR * 24;
exports = module.exports = class Cache {
constructor() {
this.defaultTime = HOUR;
this[cache] = {};
setInterval(() => {
let list = Object.keys(this[cache]);
let now = Date.now();
list.forEach(key => {
// 因为是单线程的,所以不用担心这个处理完之前有其它线程把 key 清理掉
let time = this[cache][key].time;
if (time && time <= now) {
this.del(key);
}
});
}, HOUR + MINUTE * 20); // 与默认超时时间不同,防止雪崩
}
setItem(key, value, opts) {
if (key === undefined || value === undefined) {
console.warn(`key: ${key} or value: ${value} undefined!`);
return;
}
let time = this.defaultTime;
if (opts && opts.time) {
time = opts.time;
}
this[cache][key] = {
data: value,
time: +Date.now() + time
}
return this;
}
getItem(key) {
let now = Date.now();
if (this[cache][key]) {
if (this[cache][key].time >= now) {
return this[cache][key].data;
}
else {
this.delItem(key);
}
}
return null;
}
delItem(key) {
delete this[cache][key];
return this;
}
getLength() {
return Object.keys(this[cache]).length;
}
clear() {
this[cache] = {};
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。