TIL ( Redis-cache )

2024. 8. 12. 23:24ใ†TIL

๐Ÿ’กRedis-cache

 

- nestJs์—์„œ redis ์‚ฌ์šฉํ•˜๊ธฐ๐Ÿ™‚

 

redis 

- redis๋Š” Key, Value ๊ตฌ์กฐ์˜ ๋น„์ •ํ˜• ๋ฐ์ดํ„ฐ๋ฅผ ์ €์žฅํ•˜๊ณ  ๊ด€๋ฆฌํ•˜๊ธฐ ์œ„ํ•œ ์˜คํ”ˆ ์†Œ์Šค ๊ธฐ๋ฐ˜์˜ ๋น„๊ด€๊ณ„ํ˜• ๋ฐ์ดํ„ฐ ๋ฒ ์ด์Šค ๊ด€๋ฆฌ ์‹œ์Šคํ…œ์œผ๋กœ, ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค, ์บ์‹œ, ๋ฉ”์‹œ์ง€ ๋ธŒ๋กœ์ปค๋กœ ์‚ฌ์šฉ๋˜๋ฉฐ, ์ธ๋ฉ”๋ชจ๋ฆฌ ๋ฐ์ดํ„ฐ ๊ตฌ์กฐ๋ฅผ ๊ฐ€์ง„ ์ €์žฅ์†Œ์ด๋‹ค.

(์‚ฌ์šฉ์— ๋”ฐ๋ผ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค๋กœ ์‚ฌ์šฉํ•  ์ˆ˜๋„ ์žˆ๊ณ , Cache Server๋กœ ์‚ฌ์šฉํ•  ์ˆ˜๋„ ์žˆ์Œ)

 

์ธ ๋ฉ”๋ชจ๋ฆฌ(In-memory)

- ์ธ๋ฉ”๋ชจ๋ฆฌ๋ž€ ๋ฐ์ดํ„ฐ๋ฅผ ์ปดํ“จํ„ฐ์˜ ์ฃผ ๋ฉ”๋ชจ๋ฆฌ(RAM)์— ์ €์žฅํ•˜๋Š” ๋ฐฉ๋ฒ•์„ ์˜๋ฏธํ•œ๋‹ค.

RAM์— ๋ฐ์ดํ„ฐ๋ฅผ ์ €์žฅํ•˜๊ฒŒ ๋œ๋‹ค๋ฉด ๋ฉ”๋ชจ๋ฆฌ ๋‚ด๋ถ€์—์„œ ์ฒ˜๋ฆฌ๊ฐ€ ๋˜๋ฏ€๋กœ ๋ฐ์ดํ„ฐ๋ฅผ ์ €์žฅํ•˜๊ณ  ์กฐํšŒํ•  ๋•Œ ํ•˜๋“œ๋””์Šคํฌ๋ฅผ ์˜ค๊ณ  ๊ฐ€๋Š” ๊ณผ์ •์„ ๊ฑฐ์น˜์ง€ ์•Š์•„๋„ ๋˜๊ธฐ๋•Œ๋ฌธ์— ๋””์Šคํฌ๋‚˜ ๋‹ค๋ฅธ ์˜๊ตฌ์ ์ธ ์Šคํ† ๋ฆฌ์ง€ ์žฅ์น˜์— ๋ฐ์ดํ„ฐ๋ฅผ ์ €์žฅํ•˜๋Š” ๊ฒƒ์— ๋น„ํ•ด ํ›จ์”ฌ ๋น ๋ฅธ ์†๋„๋กœ ๋ฐ์ดํ„ฐ์— ์ ‘๊ทผํ•  ์ˆ˜ ์žˆ๋‹ค.

 

redis ์‚ฌ์šฉ ์ด์œ 

 

  ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค๋Š” ๋ฐ์ดํ„ฐ๋ฅผ ๋ฌผ๋ฆฌ ๋””์Šคํฌ์— ์ง์ ‘ ์“ฐ๊ธฐ ๋•Œ๋ฌธ์— ์„œ๋ฒ„์— ๋ฌธ์ œ๊ฐ€ ๋ฐœ์ƒํ•˜์—ฌ ๋‹ค์šด๋˜๋”๋ผ๋„ ๋ฐ์ดํ„ฐ๊ฐ€ ์†์‹ค๋˜์ง€ ์•Š๋Š”๋‹ค. 

•  ์‚ฌ์šฉ์ž๊ฐ€ ๋งŽ์•„์งˆ์ˆ˜๋ก ๋งค๋ฒˆ ๋””์Šคํฌ์— ์ ‘๊ทผํ•˜๊ธฐ ๋•Œ๋ฌธ์— ๋ถ€ํ•˜ ์ฆ๊ฐ€ํ•œ๋‹ค.

=> cache server๋ฅผ ๋„์ž…ํ•˜์—ฌ ์‚ฌ์šฉํ•˜์—ฌ, cache server์—์„œ ์ฒซ ๋ฒˆ์งธ ์š”์ฒญ ์ดํ›„ ์ €์žฅ๋œ ๊ฒฐ๊ณผ๊ฐ’์„ ๋ฐ”๋กœ ๋ฐ˜ํ™˜์‹œํ‚จ๋‹ค.

 

์‚ฌ์šฉ ๋ฐฉ๋ฒ•

 

1. Redis ์„ค์น˜

npm i --save ioredis

 

2.  cache manager ์„ค์น˜

 npm install @nestjs/cache-manager cache-manager

 

3.redis.module.ts

import { Module } from '@nestjs/common';
import {
  RedisModule as NestCacheModule,
  RedisModuleOptions,
} from '@nestjs/cache-manager';
import * as redisStore from 'cache-manager-ioredis';
import { RedisService } from './cache.service';
import { ConfigService } from '@nestjs/config';

@Module({
  imports: [
    NestCacheModule.register<CacheModuleOptions>({
      useFactory: async (configService: ConfigService) => ({
        store: redisStore,
        host: configService.get<string>('REDIS_HOST'), // Redis ํ˜ธ์ŠคํŠธ
        port: configService.get<number>('REDIS_PORT'), // Redis ํฌํŠธ
        password: configService.get<string>('REDIS_PASSWORD'), // Redis ๋น„๋ฐ€๋ฒˆํ˜ธ
        ttl: configService.get<number>('REDIS_TTL'), // ์บ์‹œ ์œ ์ง€ ์‹œ๊ฐ„(์ดˆ)
      }),
      inject: [ConfigService],
    }),
  ],
  exports: [NestCacheModule],
  providers: [RedisService],
})
export class RedisModule {}

 

 

 

'TIL' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

TIL( SQL ๊ธฐ๋ณธ๋ฌธ๋ฒ• )  (0) 2024.08.14
TIL( reduce )  (0) 2024.08.13
TIL ( GUBU ํ”„๋กœ์ ํŠธ ์ค‘๊ฐ„ KPT )  (0) 2024.08.09
TIL ( Faker )  (0) 2024.08.07
TIL ( fk์™€ index)  (0) 2024.08.06