配置缓存

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import { Global, Module } from '@nestjs/common'
import { CacheModule } from '@nestjs/cache-manager'
import { MemoryCacheService } from './memory-cache.service'

@Global()
@Module({
imports: [
CacheModule.register({
ttl: 60 * 60 * 6000, // 缓存的存活时间,以毫秒为单位。(4版本以秒为单位,5版本以毫秒为单位)
max: 1000, // 表示缓存中最大允许存储的项数。
isGlobal: false, // 是否全局使用
}),
],
providers: [MemoryCacheService],
exports: [CacheModule, MemoryCacheService],
})
export class MemoryCacheModule {}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import { Inject, Injectable, Logger } from '@nestjs/common'
import { CACHE_MANAGER } from '@nestjs/cache-manager'
import { Cache } from 'cache-manager'

@Injectable()
export class MemoryCacheService {
private readonly logger = new Logger(MemoryCacheService.name)

constructor(@Inject(CACHE_MANAGER) private memoryCache: Cache) {}

async get(cacheKey: string): Promise<any> {
return this.memoryCache.get(cacheKey)
}
async set(key: string, value: any, cacheTime?: number) {
await this.memoryCache.set(key, value, cacheTime)
}
async del(key: string) {
await this.memoryCache.del(key)
}

async getStore() {
const cache = this.memoryCache.store
return cache.keys()
}
}