缓存服务方法的返回值

Cyc*_*ode 3 service caching node.js typescript nestjs

我正在使用 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 {}
Run Code Online (Sandbox Code Playgroud)

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

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

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

documentation看来我只能用这种方法来控制器,微服务和WebSockets的,但不是普通的服务?

Kim*_*ern 6

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

这是因为魔法发生在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
  }
Run Code Online (Sandbox Code Playgroud)