-
[NestJS] NestJS cachingJavaScript/NestJS 2021. 9. 5. 16:01728x90
1. npm module 설치
$ npm install cache-manager cache-manager-redis-store $ npm install -D @types/cache-manager
2. redis module
import { CacheModule, Module } from '@nestjs/common'; import * as redisStore from 'cache-manager-redis-store'; import { RedisService } from './redis.service'; @Module({ imports: [ CacheModule.registerAsync({ useFactory: () => ({ store: redisStore, host: 'localhost', port: 6379, ttl: 100000, }), }), ], providers: [RedisService], exports: [RedisService], }) export class RedisModule {}
import { CACHE_MANAGER, Inject, Injectable } from '@nestjs/common'; import { Cache } from 'cache-manager'; @Injectable() export class RedisService { constructor(@Inject(CACHE_MANAGER) private readonly cache: Cache) {} public async get(key: string) { return this.cache.get(key); } public async set(key: string, value: any, ttl?: number) { await this.cache.set(key, value, { ttl }); } }
3. redis module 적용
import { Module } from '@nestjs/common'; import { ConfirmationService } from './confirmation.service'; import { ConfirmationResolver } from './confirmation.resolver'; import { RedisModule } from '@/module/redis/redis.module'; @Module({ imports: [RedisModule], exports: [ConfirmationService], providers: [ConfirmationService, ConfirmationResolver], }) export class ConfirmationModule {}
import { RedisService } from '@/module/redis/redis.service'; import { Injectable } from '@nestjs/common'; @Injectable() export class ConfirmationService { constructor(private readonly redisService: RedisService) {} public async sendConfirmation(email: string): Promise<void> { await this.redisService.set(`signup-confirmation-${email}`, email, 600); } }
728x90'JavaScript > NestJS' 카테고리의 다른 글
[NestJs] Lifecycle events (0) 2023.09.03 [NestJS] Mapped Types (0) 2021.03.01 [NestJS] 순환 의존성(Circular Dependency) 해결 방법 (0) 2020.11.30 [NestJS] GraphQL Input Type Enum Field 사용 방법 (0) 2020.11.25 [NestJS] NestJS DataLoader (0) 2020.11.21