본문 바로가기

카테고리 없음

[Nest.js] 캐싱

캐싱을 사용해야 할 때 : 동일한 요청이 지속적으로 들어오는 경우

 

패키지 설치

$ npm i cache-manager
$ npm i -D @types/cache-manager

 

app.module.ts

import { CacheModule } from '@nestjs/common';
...
CacheModule.register({
      ttl: 60000, // 데이터 캐싱 시간(밀리 초 단위, 1000 = 1초)
      max: 100, // 최대 캐싱 개수
      isGlobal: true,  // 전역 적용
    }),
...

캐시모듈 추가

 

board.service.ts

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

@Injectable()
export class BoardService {
  constructor(
    // 새로 의존성을 주입한 캐시 매니저!
    @Inject(CACHE_MANAGER) private readonly cacheManager: Cache,
    private articleRepository: ArticleRepository,
  ) {}

생성자에 캐시 매니저 주입

  async getArticles() {
    // 1번
    const cachedArticles = await this.cacheManager.get('articles');
    if (!_.isNil(cachedArticles)) {
      return cachedArticles;
    }
    // 2번
    const articles = await this.articleRepository.find({
      where: { deletedAt: null },
      select: ['author', 'title', 'updatedAt'],
    });
    // 3번
    await this.cacheManager.set('articles', articles);
    // 4번
    return articles;
  }

1. 캐시가 존재하는지 찾아본다.

2. 캐시가 없다면 리포지토리를 통해 데이터베이스에 접근한다.

3. 결과물을 캐싱한다.

4. 결과물을 리턴한다.

5. 다시 요청이 들어왔을 때 1번으로 돌아간다.