NestJS용 강력하고 유연한 캐싱 모듈입니다. Redis 기반의 분산 캐시와 In-Memory 캐시를 지원하며, AOP(Aspect-Oriented Programming)를 활용한 선언적 캐싱을 제공합니다.
- Redis 및 In-Memory 캐싱 지원
- 멀티레벨 캐시 (L1: In-Memory, L2: Redis)
- AOP 기반 선언적 캐싱 (
@Cacheable,@CacheEvict) - SWR (Stale-While-Revalidate) 패턴 지원
- Redis Cluster 지원
- 환경변수 기반 설정
- TypeScript 완전 지원
yarn install환경변수 또는 기본값(localhost:6379)을 사용하여 CacheModule을 등록합니다.
import { Module } from '@nestjs/common';
import { CacheModule } from './cache';
@Module({
imports: [
CacheModule.forRoot(), // 설정 없이 사용
],
})
export class AppModule {}직접 Redis 설정을 제공할 수 있습니다.
import { Module } from '@nestjs/common';
import { CacheModule } from './cache';
@Module({
imports: [
CacheModule.forRoot({
host: 'my-redis-server',
port: 6379,
password: 'my-password',
}),
],
})
export class AppModule {}다른 모듈의 서비스에 의존하는 경우 forRootAsync를 사용합니다.
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { CacheModule } from './cache';
@Module({
imports: [
ConfigModule.forRoot(),
CacheModule.forRootAsync({
imports: [ConfigModule],
useFactory: (configService: ConfigService) => ({
host: configService.get('REDIS_HOST'),
port: configService.get('REDIS_PORT'),
password: configService.get('REDIS_PASSWORD'),
}),
inject: [ConfigService],
}),
],
})
export class AppModule {}import { Injectable } from '@nestjs/common';
import { CacheService } from './cache';
@Injectable()
export class MyService {
constructor(private readonly cacheService: CacheService) {}
async getData(key: string) {
// 캐시에서 데이터 조회
const cached = await this.cacheService.get<string>(key);
if (cached) {
return cached;
}
// 캐시 미스 시 데이터 생성 및 저장
const data = await this.fetchData();
await this.cacheService.set(key, data, 3600); // TTL: 1시간
return data;
}
private async fetchData() {
// 실제 데이터 fetch 로직
return 'some data';
}
}import { Injectable } from '@nestjs/common';
import { Cacheable, CacheEvict } from './cache';
@Injectable()
export class UserService {
@Cacheable({
key: 'user:#{id}',
ttl: 3600,
})
async getUser(id: string) {
// 이 메서드의 결과는 자동으로 캐싱됩니다
return { id, name: 'John Doe' };
}
@CacheEvict({
key: 'user:#{id}',
})
async updateUser(id: string, data: any) {
// 이 메서드가 호출되면 해당 캐시가 삭제됩니다
return { id, ...data };
}
}.env.example 파일을 .env로 복사하여 사용하세요.
# Redis 호스트 (기본값: localhost)
REDIS_HOST=localhost
# Redis 포트 (기본값: 6379)
REDIS_PORT=6379
# Redis 비밀번호 (선택사항)
REDIS_PASSWORD=your_password_heresrc/cache/
├── cache.module.ts # 메인 모듈
├── constant/ # 상수 정의
├── decorator/ # 캐시 데코레이터 (@Cacheable, @CacheEvict)
├── interface/ # 타입 정의
├── provider/ # 캐시 제공자 (Redis, In-Memory, Multi)
├── service/ # CacheService
├── strategy/ # AOP 전략 (Aspect)
└── type/ # 추가 타입 정의
src/cache폴더를 새 프로젝트에 복사- 필요한 의존성 설치:
yarn add @nestjs/cache-manager @toss/nestjs-aop cache-manager ioredis
- AppModule에서 CacheModule을 import
- 환경변수 설정 (선택사항)
끝! 추가 설정 없이 바로 사용할 수 있습니다.
$ yarn install# development
$ yarn run start
# watch mode
$ yarn run start:dev
# production mode
$ yarn run start:prod# unit tests
$ yarn run test
# e2e tests
$ yarn run test:e2e
# test coverage
$ yarn run test:covWhen you're ready to deploy your NestJS application to production, there are some key steps you can take to ensure it runs as efficiently as possible. Check out the deployment documentation for more information.
If you are looking for a cloud-based platform to deploy your NestJS application, check out Mau, our official platform for deploying NestJS applications on AWS. Mau makes deployment straightforward and fast, requiring just a few simple steps:
$ yarn install -g @nestjs/mau
$ mau deployWith Mau, you can deploy your application in just a few clicks, allowing you to focus on building features rather than managing infrastructure.
Check out a few resources that may come in handy when working with NestJS:
- Visit the NestJS Documentation to learn more about the framework.
- For questions and support, please visit our Discord channel.
- To dive deeper and get more hands-on experience, check out our official video courses.
- Deploy your application to AWS with the help of NestJS Mau in just a few clicks.
- Visualize your application graph and interact with the NestJS application in real-time using NestJS Devtools.
- Need help with your project (part-time to full-time)? Check out our official enterprise support.
- To stay in the loop and get updates, follow us on X and LinkedIn.
- Looking for a job, or have a job to offer? Check out our official Jobs board.
Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please read more here.
- Author - Kamil Myśliwiec
- Website - https://nestjs.com
- Twitter - @nestframework
Nest is MIT licensed.