본문 바로가기
Research/Database

nestjs_cache-manager로 redis 사용하기

by RIEM 2023. 2. 27.

NestJS 어플리케이션에 Redis를 적용해보겠습니다.

캐싱이란?

  • 캐시는 중복되거나 자주 사용하는 데이터를 저장해뒀다가 필요 시 바로 사용하는 것

Redis란?

  • open source, in-memory data structure store as a db, cache, message broker and streaming engine

redis 도커로 설치

# 이미지 다운 (docker images 로 확인 가능)
$ docker pull redis

# 컨테이너로 레디스 실행 (--name: 컨테이너 이름 설정, -p: 포트 포워딩, -d: 백그라운드에서 실행)
$ docker run --name some-redis -p 6379:6379 -d redis

# redis-cli 접속
$ docker exec -it some-redis redis-cli

redis 라이브러리 설치

$ npm install cache-manager-ioredis --save
$ npm install -D @types/cache-manager-ioredis

products.module.ts

import { CacheModule, Module } from '@nestjs/common';
import { ProductsService } from './products.service';
import { ProductsController } from './products.controller';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ProductEntity } from './entities/product.entity';
import { RaffleEntity } from '../raffles/entities/raffle.entity';
import * as redisStore from 'cache-manager-ioredis';

@Module({
  imports: [
    TypeOrmModule.forFeature([ProductEntity, RaffleEntity]),
    CacheModule.register({
      store: redisStore,
      host: 'localhost',
      port: 6379,
  }),],
  controllers: [ProductsController],
  providers: [ProductsService],
  exports: [ProductsService],
})
export class ProductModule {}

products.controller.ts

import {
  Body,
  CACHE_MANAGER,
  Controller,
  Delete,
  Get,
  Inject,
  Param,
  ParseIntPipe,
  Patch,
  Post,
  UseGuards,
} from '@nestjs/common';
import { ProductsService } from './products.service';

@ApiTags('Products')
@Controller('products')
export class ProductsController {
  constructor(
    private readonly productService: ProductsService,
  ) { }
...
  @Get('fromCache')
  findAllWithRedis() {
    return this.productService.findAllWithRedis();
  }
...

products.service.ts

import { CACHE_MANAGER, Inject, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';

import { ProductEntity } from './entities/product.entity';
import { Repository } from 'typeorm';
import { Cache } from 'cache-manager';

@Injectable()
export class ProductsService {
  constructor(
    @InjectRepository(ProductEntity) private productRepository: Repository<ProductEntity>,
    @Inject(CACHE_MANAGER) private cacheManager: Cache) { }
...
  // With redis v0.1
  async findAllWithRedis() {
    const cachedResult = await this.cacheManager.get('allProducts');
    if (cachedResult) {
      console.log(`result from Redis :D `)
      return cachedResult;
    }
    const result = await this.productRepository.find();
    await this.cacheManager.set('allProducts', result, 2)

    console.log(`normal result`)
    return result;
  }
...

Reference

댓글