Nodejs Nestjs缓存管理插件@nestjs/cache-manager的使用

Nodejs Nestjs缓存管理插件@nestjs/cache-manager的使用
[@nestjs](/user/nestjs)/cache-manager 是一个在 NestJS 应用程序中实现缓存功能的插件。它允许你轻松地将缓存机制集成到你的应用中。下面是一个简单的示例,展示如何安装和配置这个插件,并在控制器中使用它。

1. 安装依赖

首先,你需要安装 [@nestjs](/user/nestjs)/cache-manager 和你喜欢的缓存适配器(例如 Redis 或 Memory)。这里我们以 Redis 为例:

npm install [@nestjs](/user/nestjs)/cache-manager redis

2. 配置模块

接下来,在你的应用程序中配置 CacheModule。这通常在你的根模块(如 AppModule)中完成。

import { Module } from '[@nestjs](/user/nestjs)/common';
import { CacheModule, CacheInterceptor } from '[@nestjs](/user/nestjs)/cache-manager';
import * as redisStore from 'cache-manager-redis-store';

@Module({
  imports: [
    CacheModule.register({
      isGlobal: true,
      store: redisStore,
      host: 'localhost',
      port: 6379,
    }),
  ],
  providers: [
    // 如果你想全局使用缓存拦截器,可以这样注册
    {
      provide: APP_INTERCEPTOR,
      useClass: CacheInterceptor,
    },
  ],
})
export class AppModule {}

3. 使用缓存服务

现在你可以在任何服务或控制器中注入并使用 CacheManager 来执行缓存操作。

在服务中使用

import { Injectable } from '[@nestjs](/user/nestjs)/common';
import { InjectCache } from '[@nestjs](/user/nestjs)/cache-manager';
import { Cache } from 'cache-manager';

@Injectable()
export class AppService {
  constructor(@InjectCache() private cacheManager: Cache) {}

  async getHello(): Promise<string> {
    const key = 'hello';
    let data = await this.cacheManager.get(key);
    if (!data) {
      data = 'Hello World!';
      await this.cacheManager.set(key, data, { ttl: 5000 }); // 缓存5秒
    }
    return data;
  }
}

在控制器中使用

import { Controller, Get } from '[@nestjs](/user/nestjs)/common';
import { AppService } from './app.service';

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get()
  getHello(): string {
    return this.appService.getHello();
  }
}

4. 使用缓存拦截器

如果你已经将 CacheInterceptor 注册为全局拦截器,你可以直接在控制器方法上使用 @Cacheable() 装饰器来标记需要缓存的方法。

import { Controller, Get, CacheInterceptor, UseInterceptors } from '[@nestjs](/user/nestjs)/common';

@Controller()
export class AppController {
  @Get()
  @UseInterceptors(CacheInterceptor)
  @Cacheable({ ttl: 5000 }) // 缓存5秒
  getHello(): string {
    return 'Hello World!';
  }
}

以上就是使用 [@nestjs](/user/nestjs)/cache-manager 插件的基本步骤。你可以根据自己的需求调整配置和使用方式。


3 回复

当然,了解@nestjs/cache-manager插件能让你的Node.js应用飞起来!想象一下,你的应用就像个健忘的小马驹,每次都要重新思考同样的问题。而这个插件就像是给小马驹戴上了一个记忆项圈,让它记住之前的问题和答案。

首先,你需要安装它,就像给小马驹找一个合适的项圈:

npm install [@nestjs](/user/nestjs)/cache-manager redis

接着,在你的模块中引入它,就像是给小马驹套上项圈:

import { CacheModule } from '[@nestjs](/user/nestjs)/cache-manager';
import { Module } from '[@nestjs](/user/nestjs)/common';

@Module({
  imports: [
    CacheModule.register({
      isGlobal: true,
      store: require('@cache-manager/ioredis-store').default,
      host: 'localhost',
      port: 6379,
    }),
  ],
})
export class AppModule {}

现在,你可以使用它来缓存数据了,就像是教会了小马驹记住东西:

import { Cache } from '[@nestjs](/user/nestjs)/cache-manager';
import { Inject, Injectable } from '[@nestjs](/user/nestjs)/common';

@Injectable()
export class AppService {
  constructor(@Inject(Cache) private cache: Cache) {}

  async getData(key: string): Promise<any> {
    let data = await this.cache.get(key);
    if (!data) {
      // 假设这是从数据库获取数据的过程
      data = await this.expensiveOperation();
      await this.cache.set(key, data, 60); // 缓存60秒
    }
    return data;
  }

  async expensiveOperation(): Promise<any> {
    // 模拟耗时操作
    return new Promise(resolve => setTimeout(() => resolve('珍贵的数据'), 2000));
  }
}

这样,你就教会了你的应用如何记住一些事情,从而提高了效率!


@nestjs/cache-manager 是一个非常有用的 NestJS 插件,用于处理应用中的缓存需求。它封装了通用的缓存管理库 cache-manager,使得在 NestJS 应用中轻松集成和使用缓存功能变得简单。

安装

首先,你需要安装必要的依赖:

npm install @nestjs/cache-manager cache-manager

配置

接下来,在你的 NestJS 应用中配置缓存模块。你可以选择不同的缓存存储后端,例如内存、Redis 等。这里以 Redis 为例:

  1. 安装 Redis 相关依赖:

    npm install ioredis
    
  2. app.module.ts 或创建一个新的模块(如 cache.module.ts)中配置:

    import { Module } from '@nestjs/common';
    import { CacheModule, CACHE_MANAGER } from '@nestjs/cache-manager';
    import * as redisStore from 'cache-manager-ioredis';
    
    @Module({
      imports: [
        CacheModule.register({
          store: redisStore,
          host: 'localhost',
          port: 6379,
          isGlobal: true, // 设置为全局模块
        }),
      ],
      providers: [
        {
          provide: CACHE_MANAGER,
          useFactory: () => new (require('cache-manager').CacheManager)(),
        },
      ],
      exports: [CacheModule],
    })
    export class CacheModule {}
    

使用缓存

在你的服务或控制器中注入 CacheService 并使用它来设置和获取缓存数据。

import { Injectable } from '@nestjs/common';
import { InjectCache } from '@nestjs/cache-manager';
import { Cache } from 'cache-manager';

@Injectable()
export class AppService {
  constructor(@InjectCache() private readonly cache: Cache) {}

  async getHello(): Promise<string> {
    const cachedValue = await this.cache.get('hello');
    if (cachedValue) {
      return cachedValue;
    }

    // 模拟耗时操作
    const data = 'Hello World!';
    await this.cache.set('hello', data, { ttl: 5 }); // 设置缓存过期时间为5秒
    return data;
  }
}

注意事项

  • ttl 参数表示时间至过期(Time To Live),单位为秒。
  • 如果你不需要全局模块,可以去掉 isGlobal: true 并在需要使用缓存的地方导入该模块。
  • 根据实际项目需求,可能还需要对 Redis 的连接配置进行更细致的调整,比如密码认证等。

通过以上步骤,你就可以在 NestJS 应用中使用 @nestjs/cache-manager 来管理缓存了。

@nestjs/cache-manager 是 NestJS 的缓存管理插件,用于简化缓存操作。首先安装该插件:

npm install @nestjs/cache-manager cache-manager

在模块中引入 CacheModule

import { CacheModule } from '@nestjs/cache-manager';

@Module({
  imports: [CacheModule.register()],
  // ...
})
export class AppModule {}

使用时,在服务或控制器中注入 CacheManager

import { CacheManager, Inject, Injectable } from '@nestjs/common';
import { Cache } from 'cache-manager';

@Injectable()
export class MyService {
  constructor(@Inject('CACHE_MANAGER') private cacheManager: Cache) {}

  async setValue(key: string, value: any) {
    await this.cacheManager.set(key, value);
  }

  async getValue(key: string) {
    return await this.cacheManager.get(key);
  }
}

这样就可以轻松地进行缓存读写了。

回到顶部