缓存
Midway Cache 是为了方便开发者进行缓存操作的组件,它有利于改善项目的性能。它为我们提供了一个数据中心以便进行高效的数据访问。
相关信息:
描述 | |
---|---|
可用于标准项目 | ✅ |
可用于 Serverless | ✅ |
可用于一体化 | ✅ |
包含独立主框架 | ❌ |
包含独立日志 | ❌ |
安装
首先安装相关的组件模块。
$ npm i @midwayjs/cache@3 cache-manager --save
$ npm i @types/cache-manager --save-dev
或者在 package.json
中增加如下依赖后,重新安装。
{
"dependencies": {
"@midwayjs/cache": "^3.0.0",
"cache-manager": "^3.4.1",
// ...
},
"devDependencies": {
"@types/cache-manager": "^3.4.0",
// ...
}
}
使用 Cache
Midway 为不同的 cache 存储提供了统一的 API。默认内置了一个基于内存数据存储的数据中心。如果想要使用别的数据中心,开发者也可以切换到例如 mongodb、fs 等模式。
首先,引入 Cache 组件,在 configuration.ts
中导入:
import { Configuration, App } from '@midwayjs/core';
import * as cache from '@midwayjs/cache';
import { join } from 'path'
@Configuration({
imports: [
// ...
cache // 导入 cache 组件
],
importConfigs: [
join(__dirname, 'config')
]
})
export class MainConfiguration {
}
然后在业务代码中即可注入使用。
import { Inject, Provide } from '@midwayjs/core';
import { IUserOptions } from '../interface';
import { CacheManager } from '@midwayjs/cache';
@Provide()
export class UserService {
@Inject()
cacheManager: CacheManager; // 依赖注入 CacheManager
}
通过提供的 API 来设置,获取缓存数据。
import { Inject, Provide } from '@midwayjs/core';
import { IUserOptions } from '../interface';
import { CacheManager } from '@midwayjs/cache';
@Provide()
export class UserService {
@Inject()
cacheManager: CacheManager;
async getUser(options: IUserOptions) {
// 设置缓存内容
await this.cacheManager.set(`name`, 'stone-jin');
// 获取缓存内容
let result = await this.cacheManager.get(`name`);
return result;
}
async getUser2(){
//获取缓存内容
let result = await this.cacheManager.get(`name`);
return result;
}
async reset(){
await this.cacheManager.reset(); // 清空对应 store 的内容
}
}
设置缓存
我们通过 await this.cache.set(key, value)
方法进行设置,此处默认过期时间是10s。
你也可以手动设置 TTL(过期时间),如下:
await this.cacheManager.set(key, value, {ttl: 1000}); // ttl的单位为秒
如果你想要 Cache 不过期,则将 TTL 设置为 null 即可。
await this.cacheManager.set(key, value, {ttl: null});
同时你也可以通过全局的 config.default.ts
中进行设置。
export default {
// ...
cache: {
store: 'memory',
options: {
max: 100,
ttl: 10, // 修改默认的ttl配置
},
}
}