结果缓存
MikroORM 有一个简单的结果缓存机制。它适用于 EntityManager 的这些方法:find()、findOne()、findAndCount()、findOneOrFail()、count(),以及 QueryBuilder 的结果方法(包括 execute)。
默认情况下使用内存缓存,它在整个 MikroORM 实例内共享。默认过期时间是 1 秒。
const res = await em.find(Book, { author: { name: 'Jon Snow' } }, {
populate: ['author', 'tags'],
cache: 50, // 把过期时间设为 50ms
// cache: ['cache-key', 50], // 设置自定义缓存键与过期时间
// cache: true, // 使用默认缓存键与过期时间
});或者配合查询构建器:
const res = await em.createQueryBuilder(Book)
.where({ author: { name: 'Jon Snow' } })
.cache()
.getResultList();你可以在 ORM 配置中修改默认过期时间,也可以提供自定义缓存适配器:
const orm = await MikroORM.init({
resultCache: {
// 下面的选项是默认值
adapter: MemoryCacheAdapter,
expiration: 1000, // 1s
options: {},
// 缓存也可以全局启用
// global: 50, // 50ms
},
// ...
});要清除已缓存的结果,你需要用显式的缓存键加载它,之后就可以使用 em.clearCache(cacheKey) 方法。
// 把缓存键设为 'book-cache-key',过期时间为 60s
const res = await em.find(Book, { ... }, { cache: ['book-cache-key', 60_000] });
// 按名称清除该缓存键
await em.clearCache('book-cache-key');自定义缓存适配器需要实现 CacheAdapter 接口。
export interface CacheAdapter {
/**
* 从缓存中获取 `name` 键下的条目。
*/
get(name: string): Promise<any>;
/**
* 把条目写入缓存。`origin` 用于缓存失效,应该反映数据中的变更。
*/
set(name: string, data: any, origin: string, expiration?: number): Promise<void>;
/**
* 从缓存中移除该条目。
*/
remove(name: string): Promise<void>;
/**
* 清空缓存中存储的所有条目。
*/
clear(): Promise<void>;
/**
* 在 `MikroORM.close()` 内部调用,允许优雅关闭(例如对 redis)。
*/
close?(): Promise<void>;
}