Example Repository : https://github.com/easdkr/nestjs-cachemanager-with-redis
GitHub - easdkr/nestjs-cachemanager-with-redis
Contribute to easdkr/nestjs-cachemanager-with-redis development by creating an account on GitHub.
github.com
Redis Caching official Docs : https://docs.nestjs.com/techniques/caching
Documentation | NestJS - A progressive Node.js framework
Nest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with TypeScript and combines elements of OOP (Object Oriented Progamming), FP (Functional Programming), and FRP (Functional Reac
docs.nestjs.com
Nest.js의 cache manager 를 사용해 redis 를 캐시 스토어로 설정하는 간단한 연동 예제 입니다.
1. 의존성 설치
yarn add cache-manager cache-manager-ioredis
yarn add @types/cache-manager
※ nestjs의 버전과 cache-manager의 버전에 따라 호환성이 안맞을 수 있습니다. 본 예시에서 사용한 버전은 nestjs v8, cache-manager는 v4 를 사용했습니다.
2. cache module 생성
redis-cache.module.ts
import { CacheModule, Module } from '@nestjs/common';
import * as redisStore from 'cache-manager-ioredis';
import { RedisCacheService } from './redis-cache.service';
const cacheStoreRegisterConfig = {
store: redisStore,
host: 'localhost',
port: 6379,
db: 0,
ttl: 0,
};
@Module({
imports: [
CacheModule.registerAsync({
useFactory: async () => cacheStoreRegisterConfig,
}),
],
providers: [RedisCacheService],
exports: [RedisCacheService],
})
export class RedisCacheModule {}
CacheModule register 메서드의 옵션에 cache-manager-ioredis를 store로 등록해준다.
3. service 클래스
redis-cache.service.ts
import { CACHE_MANAGER, Inject, Injectable } from '@nestjs/common';
import { Cache } from 'cache-manager';
@Injectable()
export class RedisCacheService {
constructor(@Inject(CACHE_MANAGER) private readonly cacheManager: Cache) {}
async createCache(key: string, value: string): Promise<void> {
await this.cacheManager.set(key, value, { ttl: 0 });
}
async findCacheByKey(key: string): Promise<string> {
return (await this.cacheManager.get(key)) as string;
}
async deleteAll(): Promise<void> {
return await this.cacheManager.reset();
}
async deleteByKey(key: string): Promise<unknown> {
return await this.cacheManager.del(key);
}
}
간단하게 cache를 redis store에 CRD 만하는 서비스 클래스를 생성했습니다. nest로 부터 CACHE_MANAGER 토큰을 통해 cache manager 객체를 주입받아 사용합니다. 이제 RedisCacheService를 주입받아 사용할 수 있습니다.
'BackEnd > nest.js' 카테고리의 다른 글
nest.js, @nest/config, @nest/mongoose 연동 (0) | 2022.09.28 |
---|