본문 바로가기
Node js/Nest js

nest 래디스 캐시 redis cache 적용하기

by Bill Lab 2025. 2. 4.
728x90

https://docs.nestjs.com/techniques/caching

 

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 Programming), FP (Functional Programming), and FRP (Functional Rea

docs.nestjs.com

Nest 공식사이트 참고하면 자세한 설명이 나와있다.

 

핵심만 더 추려내면, 우선 필요한 npm 을 설치하자

yarn install @nestjs/cache-manager cache-manager

 

설치한 다음 redis 기반의 cacheModule 을 app module에 등록하면 된다.

import { Module } from '@nestjs/common';
import { CacheModule } from '@nestjs/cache-manager';
import { AppController } from './app.controller';

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

 

이제 사용할 준비는 끝!

 

로직에서는 어떻게 사용할 것인가?

일반적으로 위의 라이브러리는 캐싱 방법 중 "Cache Aside" 방식이다.

(cache 에 대한 제어권 처리를 백엔드 서버 내 application 에서 처리하는 것이다.)

좀더 쉽게 말하면, 여러분들이 직접 캐시 저장, 캐시에서 불러오는 로직을 코딩한다는 것이다.

(물론 Read-Through 와 비교시 장단점이 있다. - 다음기회에 다뤄보자)

 

그럼 어떻게 캐시에 있는 data 불러오고 없을 시 cache 내 data를 저장할 것인가?

간단하다!

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

@Injectable()
export class UseCase{
  constructor(
    private readonly searchService: SearchService,
    @Inject(CACHE_MANAGER) private readonly cacheManager: Cache,
  ) {}

  async execute(): Promise<data[]> {
    let searchResult = (await this.cacheManager.get('keySearchResult')) as Nullable<data[]>;

    if (!searchResult) {
      searchResult = await this.searchService.getInfo();
      await this.cacheManager.set('keySearchResult', searchResult);
    }

    return searchResult;
  }
 
}

 

@Inject(CACHE_MANAGER) private readonly cacheManager: Cache  를 이용하여 캐시에 저장할 data 불러올 data를 직접 제어할 수 있다.

 

 

동작순서

1. 캐시에 해당 data 가 있는지 확인

2. 없으면 db 에서 조회

3. 조회 된 값을 캐시에 저장

4. 조회 된 값 return 

728x90