缓存(Cache)
Midway Cache 是为了方便开发者进行缓存操作的组件,它有利于改善项目的性能。它为我们提供了一个数据中心以便进行高效的数据访问。
安装
首先安装相关的组件模块。
$ npm install @midwayjs/cache@2 cache-manager -S
$ npm install @types/cache-manager -D
使用 Cache
Midway 为不同的 cache 存储提供了统一的 API。默认内置了一个基于内存数据存储的数据中心。如果想要使用别的数据中心,开发者也可以切换到例如 mongodb、fs 等模式。
首先,引入 Cache 组件,在 configuration.ts 中导入:
import { Configuration, App } from '@midwayjs/decorator';
import { Application } from '@midwayjs/koa';
import * as bodyParser from 'koa-bodyparser';
import * as cache from '@midwayjs/cache'; // 导入cacheComponent模块
import { join } from 'path';
@Configuration({
imports: [
cache, // 导入 cache 组件
],
importConfigs: [join(__dirname, 'config')],
})
export class ContainerLifeCycle {}
然后在业务代码中即可注入使用。
import { Inject, Provide } from '@midwayjs/decorator';
import { IUserOptions } from '../interface';
import { CacheManager } from '@midwayjs/cache';
@Provide()
export class UserService {
@Inject()
cache: CacheManager; // 依赖注入CacheManager
}
通过提供的 API 来设置,获取缓存数据。
import { Inject, Provide } from '@midwayjs/decorator';
import { IUserOptions } from '../interface';
import { CacheManager } from '@midwayjs/cache';
@Provide()
export class UserService {
@Inject()
cache: CacheManager;
async getUser(options: IUserOptions) {
// 设置缓存内容
await this.cache.set(`name`, 'stone-jin');
// 获取缓存内容
let result = await this.cache.get(`name`);
return result;
}
async getUser2() {
//获取缓存内容
let result = await this.cache.get(`name`);
return result;
}
async reset() {
await this.cache.reset(); // 清空对应 store 的内容
}
}
设置缓存
我们通过 await this.cache.set(key, value) 方法进行设置,此处默认过期时间是 10s。
你也可以手动设置 TTL(过期时间),如下:
await this.cache.set(key, value, { ttl: 1000 }); // ttl的单位为秒
如果你想要禁止 Cache 不过期,则将 TTL 设置为 null 即可。
await this.cache.set(key, value, { ttl: null });
同时你也可以通过全局的 config.default.ts 中进行设置。
export const cache = {
store: 'memory',
options: {
max: 100,
ttl: 10, // 修改默认的ttl配置
},
};
获取缓存
const value = await this.cache.get(key);
如果获取不到,则为 undefined。