tuigun 2022. 9. 28. 02:29

nest.js

Cache

  • 최근에 요청된 데이터가 금방 다시 요청 될 가능성이 높을 때 캐시에 저장한다
  • DB에 접근하여 데이터를 가져오는 것 보다 빠름

Nest cache

  • Nest.js에서 자체적으로 캐싱을 제공하고있다.
  • 캐시 인터셉터에 대한 코드는 nest.js 레포지토리에서 제공하고있다.
  • 캐싱된 데이터는 기본적으로 서버의 메모리 내에 저장된다. (로컬캐시)
  • 로드밸런서가 요청을 분산하는 경우, 동일한 요청이 다른 노드로 이동하면서 캐시 누락이 될 수 있음
  • 공식문서에 따르면 Nest.js의 캐시를 사용하다가 Redis와 같은 인메모리 DB로도 쉽게 마이그레이션 가능한 것 같다.

Cache interceptor code

@Injectable()
export class CacheInterceptor implements NestInterceptor {
  @Optional()
  @Inject(HTTP_ADAPTER_HOST)
  protected readonly httpAdapterHost: HttpAdapterHost;

  protected allowedMethods = ['GET'];
  constructor(
    @Inject(CACHE_MANAGER) protected readonly cacheManager: any,
    @Inject(REFLECTOR) protected readonly reflector: any,
  ) {}

  async intercept(
    context: ExecutionContext,
    next: CallHandler,
  ): Promise<Observable<any>> {
    // 캐시처리할 수 있는 요청인지 확인
    const key = this.trackBy(context);

    // ttl 확인
    const ttlValueOrFactory =
      this.reflector.get(CACHE_TTL_METADATA, context.getHandler()) ?? null; 

    if (!key) { // key 생성이 안되었을 때, 비즈니스 로직으로 돌아간다.
      return next.handle();
    }
    try {
      // 캐시된 데이터를 검색, 없으면 null을 리턴
      const value = await this.cacheManager.get(key); 
      if (!isNil(value)) { // 캐시된 데이터가 있는 경우, 해당 데이터 리턴
        return of(value);
      }

      // 캐시된 데이터가 없는 경우, 캐시 데이터를 추가한다.
      const ttl = isFunction(ttlValueOrFactory)
        ? await ttlValueOrFactory(context)
        : ttlValueOrFactory;
      return next.handle().pipe(
        tap(response => {
          // ttl을 수동으로 지정하거나 기본값인 5초로 지정할 수 있음
          const args = isNil(ttl) ? [key, response] : [key, response, { ttl }];
          // 캐시에 데이터를 추가
          this.cacheManager.set(...args); 
        }),
      );
    } catch {
      return next.handle(); 
    }
  }

 

 

 

참고한 글

https://docs.nestjs.com/techniques/caching#different-stores

https://github.com/nestjs/nest/blob/ad39c3cfd78e94f191d51ae5799ad9dadb522d38/packages/common/cache/interceptors/cache.interceptor.ts

 

GitHub - nestjs/nest: A progressive Node.js framework for building efficient, scalable, and enterprise-grade server-side applica

A progressive Node.js framework for building efficient, scalable, and enterprise-grade server-side applications on top of TypeScript & JavaScript (ES6, ES7, ES8) 🚀 - GitHub - nestjs/nest: A pro...

github.com

 

Documentation | NestJS - A progressive Node.js framework

Nest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with TypeScript and combines elements of OOP (Object Oriented Progamming), FP (Functional Programming), and FRP (Functional Reac

docs.nestjs.com

https://hwasurr.io/nestjs/caching/

 

Nestjs REST 애플리케이션의 캐시 처리와 캐시 무효화

Nestjs REST 애플리케이션에서 캐시에 대한 전반적인 내용을 다룹니다. 캐시를 등록하는 방법과 캐시를 무효화하는 방법에 대해서 살펴보며 더 효율적인 방식을 찾아나갑니다.

hwasurr.io