memory-cache.js
1.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/**
* memoryCache
* @author: yyq<yanqing.yang@yoho.cn>
* @date: 2018/07/23
*/
const _ = require('lodash');
module.exports = class memoryCache {
constructor(options) {
this.options = Object.assign({}, options);
this.cache = {};
this.map = [];
this.options.maxLength = parseInt(this.options.maxLength, 10) || 1000;
}
_deleteCache(key) {
delete this.cache[key];
}
_deleteMap(key) {
_.remove(this.map, (n) => {
return n === key;
});
}
_getNowTime() {
return new Date().getTime() / 1000;
}
// 获取缓存数据
get(key) {
if (!this.cache.hasOwnProperty(key)) {
return;
}
let info = this.cache[key];
// 校验过期时间
if (info.exptime && info.exptime - this._getNowTime() < 0) {
this.clear(key);
return;
}
return _.cloneDeep(info.value);
}
// 设置缓存数据
set(key, value, exptime) {
this.cache.hasOwnProperty(key) && this._deleteMap(key);
this.map.push(key);
this.cache[key] = {
value: _.cloneDeep(value),
exptime: exptime ? (exptime + this._getNowTime()) : 0 // 过期时间
};
const maxLength = this.options.maxLength;
// 清除老旧数据
if (this.map.length > maxLength) {
let len = this.map.length - maxLength;
for (let i = 0; i < len; i++) {
this._deleteCache(this.map.shift());
}
}
}
// 清除单条缓存数据
clear(key) {
if (this.cache.hasOwnProperty(key)) {
this._deleteMap(key);
this._deleteCache(key);
}
}
// 清除所有缓存数据
clearAll() {
this.cache = {};
this.map = [];
}
};