NestJS 缓存

548 阅读2分钟

官网

缓存

缓存是一个很棒而简单的 technique,有助于提高应用的性能。 它充当提供高性能数据访问的临时数据存储。

安装

yarn add @nestjs/cache-manager cache-manager

tip:

官网采用的版本 v4

本文v5

  • 如果使用 cache-manager v4,以秒为单位提供 ttl
  • 如果使用 cache-manager v5,以毫秒为单位提供 ttl

xxx.module.ts 注入

// 引入
import { CacheModule } from "@nestjs/cache-manager"

//注入imports
CacheModule.register(),
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ConfigModule } from '@nestjs/config';
import env from './env/index';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AuthModule } from './auth/auth.module';
import { UserModule } from './user/user.module';
import { CacheModule } from "@nestjs/cache-manager"

@Module({
  imports: [
    ConfigModule.forRoot({ isGlobal: true, load: [env] }),
    CacheModule.register(),
    AuthModule,
    UserModule,
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

xxx.controller.ts

要与缓存管理器实例交互,请使用 CACHE_MANAGER 令牌将其注入你的类,如下所示:

import { Body, Controller, Get, Query, Post, Inject } from '@nestjs/common';
import { AppService } from './app.service';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { Cache } from 'cache-manager';
import { Public } from './auth/public.guard'

@Controller()
@Public()
export class AppController {
  constructor(
    private readonly appService: AppService,
    @Inject(CACHE_MANAGER) private cache: Cache,
  ) {}

  // Example
  @Get()
  async saveCache() {
    await this.cache.set('cache',"测试cache",5000*10)
    return "已存"
  }

  @Get('cache')
  async getCache(){
    const c = await this.cache.get("cache")
    console.log("获取了cache",c)
    return c
  }
}

set:

@params key:string

@params value:any

@params ttl number

要禁用缓存过期,请将 ttl 配置属性设置为 0

del(key:string) 删除某个

reset() 清除整个缓存

运行查看

存入

image.png 获取

image.png

自定义缓存#

所有缓存数据都有自己的过期时间 (TTL)。 要自定义默认值,请将选项对象传递给 register() 方法。

CacheModule.register({
  ttl: 5*1000, // seconds
  max: 10, // maximum number of items in cache
});

全局使用模块#

当你想在其他模块中使用 CacheModule 时,你需要导入它(这是任何 Nest 模块的标准)。 或者,通过将选项对象的 isGlobal 属性设置为 true 来将其声明为 全局模块,如下所示。 在这种情况下,一旦 CacheModule 被加载到根模块(例如,AppModule)中,你就不需要在其他模块中导入它。

CacheModule.register({
  isGlobal: true,
});