/
LruCache.idl
105 lines (84 loc) · 3.8 KB
/
LruCache.idl
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/*! @brief LruCache(Least Recently Used Cache) 是用来维护LRU缓存的类。它可以存储一定数量的值,并且保持了容器的尺寸。当新数据进来时,如果容器还没有到达尺寸限制,新数据可以直接加入到容器中。如果容器已满,则容器将淘汰最近最少使用的数据
我们可以通过如下方式来使用:
```JavaScript
const util = require('util')
const c = new util.LruCache(10, 100) // create a LruCache instance with size 10 and timeout 100ms
```
其中,set() 是设置键值对的接口:
```JavaScript
LruCache.set(String name, Value value);
```
name 参数指定要设定的键值,value 参数指定要设定的值。
`LruCache` 的 `get` 方法可以用回调函数的方式更新缓存数据:
```JavaScript
var c = new util.LruCache(10, 1000); // create a LruCache instance with size 10 and timeout 1000ms
function get_data(name) {
// return data from backend
// ...
var data = {'name': name, 'value': Math.random()};
console.log('update data: ' + JSON.stringify(data)); // output infomation to console
return data;
}
console.log(c.get('a', get_data));
console.log(c.get('a', get_data));
```
执行结果:
```sh
update data: {"name":"a","value":0.4019124971556616}
{"name":"a","value":0.4019124971556616} // updater will be called to update cache data when cache is empty
{"name":"a","value":0.4019124971556616} // updater will not be called when cache is not empty
```
具体使用 LruCache 时,建议开发人员遵循以下的最佳实践:
- 可以在后端数据处理过程中,以某个特定时间点为新鲜点,设定失效时间,来使用 LruCache 优化应用性能。
- 在对应的场景下分析业务决策。例如更频发的数据更新,需要配置更短的失效时间,而更新频率较低的缓存数据则不需要设定太短的失效时间。
- 在不同使用场景中,考虑不同数据访问模式,使用合适的 LruCache 类实例。
*/
interface LruCache : EventEmitter
{
/*! @brief LruCache 对象构造函数
@param size 缓存最大尺寸
@param timeout 元素失效时间,单位是 ms,小于等于 0 不失效,缺省为 0
*/
LruCache(Integer size, Integer timeout = 0);
/*! @brief 查询容器内数值个数 */
readonly Integer size;
/*! @brief 查询和设置容器内元素失效时间,单位是 ms,小于等于 0 不失效 */
Integer timeout;
/*! @brief 清除容器数据 */
clear();
/*! @brief 检查容器内是否存在指定键值的数据
@param name 指定要检查的键值
@return 返回键值是否存在
*/
Boolean has(String name);
/*! @brief 查询指定键值的值
@param name 指定要查询的键值
@return 返回键值所对应的值,若不存在,则返回 undefined
*/
Value get(String name);
/*! @brief 查询指定键值的值,若不存在或过期,则调用回调函数更新数据
@param name 指定要查询的键值
@param updater 指定更新函数
@return 返回键值所对应的值
*/
Value get(String name, Function updater);
/*! @brief 设定一个键值数据,键值不存在则插入一条新数据
@param name 指定要设定的键值
@param value 指定要设定的数据
*/
set(String name, Value value);
/*! @brief 设定一个键值数据,键值不存在则插入新数据
@param map 指定要设定的键值数据字典
*/
set(Object map);
/*! @brief 删除指定键值的全部值
@param name 指定要删除的键值
*/
remove(String name);
/*! @brief 检查容器是否为空
@return 容器内无数值则返回 true
*/
Boolean isEmpty();
/*! @brief 查询和绑定数据超时事件,相当于 on("expire", func); */
Function onexpire;
};