【问题标题】:Caching return value from a service method缓存服务方法的返回值
【发布时间】:2020-06-13 02:48:11
【问题描述】:

我正在使用 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.js typescript caching service nestjs


    【解决方案1】:

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

    这是因为魔法发生在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
      }
    

    【讨论】:

    • 是的,我也发现了这种方法,虽然我的方法在实际设置缓存之前多次运行时遇到问题,但这并不是与缓存相关的真正问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-13
    • 2013-04-06
    • 1970-01-01
    • 1970-01-01
    • 2018-08-08
    相关资源
    最近更新 更多