首页 > 解决方案 > 缓存服务方法的返回值

问题描述

我正在使用nestjs并且刚刚安装了cache-manager模块并试图缓存来自服务调用的响应。

我在示例模块(sample.module.ts)中注册了缓存模块:

import { CacheInterceptor, CacheModule, Module } from '@nestjs/common';
import { SampleService } from './sample.service';
import { APP_INTERCEPTOR } from '@nestjs/core';
import * as redisStore from 'cache-manager-redis-store';


@Module({
  imports: [
    CacheModule.register({
      ttl: 10,
      store: redisStore,
      host: 'localhost',
      port: 6379,
    }),
 ],
 providers: [
   SampleService,
   {
     provide: APP_INTERCEPTOR,
     useClass: CacheInterceptor,
   }
 ],
 exports: [SampleService],
})
export class SampleModule {}

然后在我的服务中(sample.service.ts):

@Injectable()
export class SampleService {
  @UseInterceptors(CacheInterceptor)
  @CacheKey('findAll')
  async findAll() {
    // Make external API call
  }
}

查看 redis 我可以看到服务方法调用没有缓存任何内容。如果我对控制器使用相同的方法,那么一切正常,我可以在我的 redis 数据库中看到缓存的条目。我认为没有办法在nestjs中缓存单个服务方法调用。

阅读documentation似乎我只能将这种方法用于控制器、微服务和 websockets,而不能用于普通服务?

标签: node.jstypescriptcachingservicenestjs

解决方案


正确,不能以与控制器相同的方式对服务使用缓存。

这是因为魔法发生在CacheInterceptor并且Interceptors只能在 中使用Controllers


但是,您可以将其cacheManager注入您的服务并直接使用它:

export class SampleService {

  constructor(@Inject(CACHE_MANAGER) protected readonly cacheManager) {}  

  findAll() {
    const value = await this.cacheManager.get(key)
    if (value) {
      return value
    }

    const respone = // ...
    this.cacheManager.set(key, response, ttl)
    return response
  }

推荐阅读