[NestJs] In-Memory Cache

Dragon_Tack·2023년 11월 15일
0
post-thumbnail

인스턴스 내에 쉽게 메모리 저장해서 DB 호출수 줄이기
요새 DB에 connection 횟수를 줄이는 방법에 대해 고민이 많다.
추후에는 Cache서버를 구축해서 사용 해야겠지만,,? 그전에 In-memory-Cache 기능을 사용해보려고 한다.

npm install --save @nestjs/cache-manager

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 {}

키를 이용해서 가져오기

const value = await this.cacheManager.get('key');

값 설정하기

await this.cacheManager.set('key', 'value', 1000);

값 리셋하기

await this.cacheManager.reset();

이 기본 설정을 통해 NestJS 애플리케이션에서 캐싱을 시작할 수 있다.
고도화 된 프로젝트에서는 Key가 많아지면 인스턴스에 부하가 오면 어떡하지? 라는 생각이지만
가볍거나 잘 바뀌지 않는값을 불필요한 호출을 줄이기 좋은 것같다 👩‍💻🚀

Heap Out Of Memory에 주의하세요....

참고문헌 : https://docs.nestjs.com/techniques/caching#in-memory-cache

profile
고민의 흔적을 늘여놓는 공간

0개의 댓글