ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [NestJS] NestJS caching
    JavaScript/NestJS 2021. 9. 5. 16:01
    728x90

    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
Designed by Tistory.