memory-cache.js
1.62 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
/**
* memoryCache
* @author: yyq<yanqing.yang@yoho.cn>
* @date: 2018/07/23
*/
const _ = require('lodash');
function _clearArray(list, key) {
_.remove(list, (n) => {
return n === key;
});
}
function _clearObject(obj, key) {
delete obj[key];
}
function _getNowTime() {
return new Date().getTime() / 1000;
}
module.exports = function memoryCache(maxLength = 1000) {
let cache = {};
let mapList = [];
// 获取缓存数据
this.get = (key) => {
if (!cache.hasOwnProperty(key)) {
return;
}
let info = cache[key];
// 校验过期时间
if (info.exptime && info.exptime - _getNowTime() < 0) {
this.clear(key);
return;
}
return info.value;
};
// 设置缓存数据
this.set = (key, value, exptime) => {
cache.hasOwnProperty(key) && _clearArray(mapList, key);
mapList.push(key);
cache[key] = {
value,
exptime: exptime ? (exptime + _getNowTime()) : 0 // 过期时间
};
// 清除老旧数据
if (mapList.length > maxLength) {
let len = mapList.length - maxLength;
for (let i = 0; i < len; i++) {
_clearObject(cache, mapList.shift());
}
}
};
// 清除单条缓存数据
this.clear = (key) => {
if (cache.hasOwnProperty(key)) {
_clearArray(mapList, key);
_clearObject(cache, key);
}
};
// 清除所有缓存数据
this.clearAll = () => {
cache = {};
mapList = [];
};
return this;
};