@geektech/backone-utils
缓存
TTL 惰性过期与 LRU 容量淘汰,getOrSet 工厂。
cache 模块是纯内存缓存:TtlCache(TTL 惰性过期、无容量限制)与 LruCache(容量上限 + LRU 淘汰,可选过期)实现同一 Cache 接口,可互换使用(依赖倒置),通过 createCache 工厂按选项选择策略。
创建缓存
ts
import { createCache } from '@geektech/backone-utils';
// TTL 缓存:10 分钟过期
const cache = createCache({ ttlMs: 10 * 60 * 1000 });
// LRU 缓存:最多 100 条,逐出最久未访问
const lru = createCache({ capacity: 100, ttlMs: 60_000 });基本操作
ts
cache.set('key', { user: 'alice' });
cache.get('key'); // 命中返回值;未命中或已过期返回 undefined
cache.has('key'); // 是否存在未过期的条目
cache.delete('key'); // 删除,返回是否删除成功
cache.clear(); // 清空全部
cache.size; // 当前条目数getOrSet
命中则直接返回,未命中则执行工厂并写入(工厂可为异步,适合缓存数据库查询等耗时结果):
ts
const user = await cache.getOrSet(`user:${id}`, async () => {
return await db.query`SELECT * FROM users WHERE id = ${id}`;
});接口说明
| 成员 | 说明 |
|---|---|
get / set | 读写;set 可传 ttlMs 覆盖默认过期,都不传则永不过期 |
has / delete / clear / size | 存在判断 / 删除 / 清空 / 条目数 |
getOrSet | 未命中执行工厂并写入 |
注意
值不允许为 undefined:undefined 视为未命中。