缓存
缓存是一个伟大而简单的技术,有助于提高你的应用程序的性能。本组件提供了缓存相关的能力,你可以将数据缓存到不同的数据源,也可以针对不同场景建立多级缓存,提高数据访问速度。
提示
Midway 提供基于 cache-manager v5 模块重新封装了缓存组件,原有的缓存模块基于 v3 开发不再迭代,如需查看老文档,请访问 这里。
相关信息:
描述 | |
---|---|
可用于标准项目 | ✅ |
可用于 Serverless | ✅ |
可用于一体化 | ✅ |
包含独立主框架 | ❌ |
包含独立日志 | ❌ |
安装
首先安装相关的组件模块。
$ npm i @midwayjs/cache-manager@3 --save
或者在 package.json
中增加如下依赖后,重新安装。
{
"dependencies": {
"@midwayjs/cache-manager": "^3.0.0",
// ...
},
}
启用组件
首先,引入组件,在 configuration.ts
中导入:
import { Configuration } from '@midwayjs/core';
import * as cacheManager from '@midwayjs/cache-manager';
import { join } from 'path'
@Configuration({
imports: [
// ...
cacheManager,
],
importConfigs: [
join(__dirname, 'config')
]
})
export class MainConfiguration {
}
使用缓存
1、配置缓存
在使用前,你需要配置缓存所在的位置,比如内置的内存缓存,或者是引入 Redis 缓存,每个缓存对应了一个缓存的 Store。
下面的示例代码,配置了一个名为 default
的内存缓存。
// src/config/config.default.ts
export default {
cacheManager: {
clients: {
default: {
store: 'memory',
},
},
}
}
最常用的场景下,缓存会包含两个参数,配置 max
修改缓存的数量,配置 ttl
修改缓存的过期时间,单位毫秒。
// src/config/config.default.ts
export default {
cacheManager: {
clients: {
default: {
store: 'memory',
options: {
max: 100,
ttl: 10,
},
},
},
}
}
提示
ttl
的单位是毫秒max
代表缓存 key 的最大个数- 不同的 Store 淘汰 key 的算法不同,内存缓存使用的淘汰算法是 LRU
2、使用缓存
可以通过服务工厂的装饰器获取到实例,可以通过简单的 get
和 set
方法获取和保存缓存。
import { InjectClient, Provide } from '@midwayjs/core';
import { CachingFactory, MidwayCache } from '@midwayjs/cache-manager';
@Provide()
export class UserService {
@InjectClient(CachingFactory, 'default')
cache: MidwayCache;
async invoke(name: string, value: string) {
// 设置缓存
await this.cache.set(name, value);
// 获取缓存
const data = await this.cache.get(name);
// ...
}
}
动态设置 ttl
过期时间。
await this.cache.set('key', 'value', 1000);
若要禁用缓存过期,可以将 ttl
配置属性设置为 0。
await this.cache.set('key', 'value', 0);
删除单个缓存。
await this.cache.del('key');
清理整个缓存,可以使用 reset
方法。
await this.cacheManager.reset();
危险
注意,清理整个缓存非常危险,如果使用了 Redis 作为缓存 store,将清空整个 Redis 数据。
除了装饰器之外,也可以通过 API 获取缓存实例。
import { InjectClient, Provide } from '@midwayjs/core';
import { CachingFactory, MidwayCache } from '@midwayjs/cache-manager';
@Provide()
export class UserService {
@Inject()
cachingFactory: CachingFactory;
async invoke() {
const caching = await this.cachingFactory.get('default');
// ...
}
}