结果缓存
MikroORM 有一个简单的结果缓存机制。它与 EntityManager
的那些方法一起工作:find()
、findOne()
、findAndCount()
、findOneOrFail()
、count()
,以及 QueryBuilder
结果方法(包括 execute
)。
¥MikroORM has a simple result caching mechanism. It works with those methods of EntityManager
: find()
, findOne()
, findAndCount()
, findOneOrFail()
, count()
, as well as with QueryBuilder
result methods (including execute
).
默认情况下,使用内存缓存,该缓存在整个 MikroORM
实例中共享。默认到期时间为 1 秒。
¥By default, in memory cache is used, that is shared for the whole MikroORM
instance. Default expiration is 1 second.
const res = await em.find(Book, { author: { name: 'Jon Snow' } }, {
populate: ['author', 'tags'],
cache: 50, // set expiration to 50ms
// cache: ['cache-key', 50], // set custom cache key and expiration
// cache: true, // use default cache key and expiration
});
或使用查询构建器:
¥Or with query builder:
const res = await em.createQueryBuilder(Book)
.where({ author: { name: 'Jon Snow' } })
.cache()
.getResultList();
我们可以在 ORM 配置中更改默认过期时间并提供自定义缓存适配器:
¥We can change the default expiration as well as provide custom cache adapter in the ORM configuration:
const orm = await MikroORM.init({
resultCache: {
// following options are the defaults
adapter: MemoryCacheAdapter,
expiration: 1000, // 1s
options: {},
// cache can be also enabled globally
// global: 50, // 50ms
},
// ...
});
要清除缓存结果,我们需要使用显式缓存键加载它,稍后我们可以使用 em.clearCache(cacheKey)
方法。
¥To clear the cached result, we need to load it with explicit cache key, and later on we can use em.clearCache(cacheKey)
method.
// set the cache key to 'book-cache-key', with expiration of 60s
const res = await em.find(Book, { ... }, { cache: ['book-cache-key', 60_000] });
// clear the cache key by name
await em.clearCache('book-cache-key');
自定义缓存适配器需要实现 CacheAdapter
接口。
¥Custom cache adapters need to implement CacheAdapter
interface.
export interface CacheAdapter {
/**
* Gets the items under `name` key from the cache.
*/
get(name: string): Promise<any>;
/**
* Sets the item to the cache. `origin` is used for cache invalidation and should reflect the change in data.
*/
set(name: string, data: any, origin: string, expiration?: number): Promise<void>;
/**
* Removes the item from cache.
*/
remove(name: string): Promise<void>;
/**
* Clears all items stored in the cache.
*/
clear(): Promise<void>;
/**
* Called inside `MikroORM.close()` Allows graceful shutdowns (e.g. for redis).
*/
close?(): Promise<void>;
}