$ npm i @nestjs/cache-manager cache-manager cache-manager-ioredis $ npm i -D @types/cache-manager @types/cache-manager-ioredis
import { BoardController } from './board.controller'; import { BoardService } from './board.service'; import { TypeOrmModule } from '@nestjs/typeorm'; import { Board } from './board.entity'; import { CacheModule } from '@nestjs/cache-manager'; import * as redisStore from 'cache-manager-ioredis'; @Module({ imports: [ TypeOrmModule.forRoot({ type: 'mysql', host: 'localhost', port: 3306, username: 'root', password: 'password', database: 'mydb', autoLoadEntities: true, synchronize: true, logging: true, }), TypeOrmModule.forFeature([Board]), CacheModule.register({ store: redisStore, host: 'localhost', port: 6379, ttl: 60, }), ], controllers: [BoardController], providers: [BoardService], }) export class AppModule {}
import { Inject, Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Board } from './board.entity'; import { Repository } from 'typeorm'; import { CACHE_MANAGER, Cache } from '@nestjs/cache-manager'; @Injectable() export class BoardService { constructor( @InjectRepository(Board) private boardRepository: Repository<Board>, @Inject(CACHE_MANAGER) private cacheManager: Cache, ) {} async getBoards(page: number, size: number): Promise<Board[]> { const cacheKey = `boards:page:${page}:size:${size}`; const cachedData = await this.cacheManager.get<Board[]>(cacheKey); if (cachedData) { return cachedData; } const skip = (page - 1) * size; const boards = await this.boardRepository.find({ order: { createdAt: 'desc', }, skip: skip, take: size, }); await this.cacheManager.set(cacheKey, boards); return boards; } }

$ redis-cli $ keys * # Redis에 저장되어 있는 모든 key 조회 $ get getBoards::boards:page:1:size:10 # 특정 key의 Value 조회 $ ttl getBoards::boards:page:1:size:10 # 특정 key의 TTL 조회