@ 经纪人/ tlcache
用于节点和浏览器的 LRU TRL 缓存
- 含有可配置的过期条目数的缓存 .
- 读取已过期的条目会将其从缓存中移除 .
- 当缓存满了, 最近使用d 条目首先被删除.
安装
npm install @brokerloop/ttlcache --save
用法( 文本脚本)
import { TTLCache } from '@brokerloop/ttlcache';
const cache = new TTLCache<string, number>({
ttl: 5000,
max: 10,
clock: Date
});
cache.set('a', 123);
cache.has('a'); // true
cache.get('a'); // 123
cache.get('b'); // undefined
cache.delete('a'); // 123
cache.empty.on(() => {
// cache is empty
});
cache.full.on(() => {
// cache is full
});
cache.evict.on(({ key, val }) => {
// entry evicted
});
选项
{
ttl: 1000, // default entry TTL in ms
max: Infinity, // max number of entries in cache
clock: Date as Clock // cache-relative clock
}
clock
默认情况下,缓存使用 Date.now() 以备过期的条目。 这在系统日期/时间不变的情况下有效. 你可以自行执行 Clock 接口 :
interface Clock {
now: () => number; // must be monotonically increasing
[_: string]: any;
}
const clock = (() => {
let time = 0;
const clock: Clock = {
now: () => time,
pass: (ms: number) => time += ms
};
return clock;
})();
属性
size
返回缓存的大小,包括已过期的条目。 运行 cleanup() 首先获取有效的缓存大小.
方法
keys(): Iterator<K>
返回从最新到最老的有效缓存条目密钥上的浏览器 。 过期的条目不被拆迁.
values(): Iterator<V>
返回从最新到最古老的有效缓存条目值的浏览器。 过期的条目不被拆迁.
entries(): Iterator<{ key: K, val: V }>
返回从最新到最老的有效缓存条目的浏览器。 过期的条目不被拆迁.
has(key: K): boolean
检查是否 key 在缓存中存在。 过期时不驱逐该条目.
get(key: K): V|undefined
按给定条目查找 key. 回归 undefined 如果未找到或该条目已过期,也可将其驱逐.
set(key: K, val: V): void
创建条目于 key如果缓存满了,则将缓存的 LRU 条目驱逐出境。 如果已过期的条目存在于 key它的LRU年龄被刷新,但并没有被逐出.
delete(key: K): V|undefined
查找并删除条目 : key。如果条目值被删除,则返回,或者 undefined 否则.
cleanup(opts = { emit: true }): void
Evicts 缓存中所有已过期的条目 。 过 emit: false 无法发射 evict 事件.
resize(max: number, opts = { emit: true }): void
将缓存大小调整到给定 max 尺寸。 当成长时,没有任何条目被逐出. 在收缩时,根据需要,按最年长的路轮运输公司年龄,将入口驱逐,直到新的 max 已经到达。 过 emit: false 无法发射 evict 事件.
clear(): void
启用缓存, 删除所有条目, 不显示发射信号 .
活动(通过) 信号(中文(简体) )
empty
缓存变成空后发射信号 。 不要开火 clear()。 。 。 .
full
缓存满后发射信号.
evict
缓存进入后发射信号 。 被逐出门 { key: K, val: V } 被通过作为一个争论。 不要开火 delete() 财务报告和审定财务报表 clear()。 。 。 .