1 Star 0 Fork 0

lsw / 算法和数据结构

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
cache.js 1.71 KB
一键复制 编辑 原始数据 按行查看 历史
lsw 提交于 2019-01-08 10:32 . 添加缓存方法;
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] = {};
}
}
NodeJS
1
https://gitee.com/lsw0123/algorithm_and_data_structure.git
git@gitee.com:lsw0123/algorithm_and_data_structure.git
lsw0123
algorithm_and_data_structure
算法和数据结构
d36e0c1710e3842996082ec40401992f4f102ebb

搜索帮助