728x90
NestJS 어플리케이션에 Redis를 적용해보겠습니다.
캐싱이란?
- 캐시는 중복되거나 자주 사용하는 데이터를 저장해뒀다가 필요 시 바로 사용하는 것
Redis란?
- open source, in-memory data structure store as a db, cache, message broker and streaming engine
redis 도커로 설치
# 이미지 다운 (docker images 로 확인 가능)
$ docker pull redis
# 컨테이너로 레디스 실행 (--name: 컨테이너 이름 설정, -p: 포트 포워딩, -d: 백그라운드에서 실행)
$ docker run --name some-redis -p 6379:6379 -d redis
# redis-cli 접속
$ docker exec -it some-redis redis-cli
redis 라이브러리 설치
$ npm install cache-manager-ioredis --save
$ npm install -D @types/cache-manager-ioredis
products.module.ts
import { CacheModule, Module } from '@nestjs/common';
import { ProductsService } from './products.service';
import { ProductsController } from './products.controller';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ProductEntity } from './entities/product.entity';
import { RaffleEntity } from '../raffles/entities/raffle.entity';
import * as redisStore from 'cache-manager-ioredis';
@Module({
imports: [
TypeOrmModule.forFeature([ProductEntity, RaffleEntity]),
CacheModule.register({
store: redisStore,
host: 'localhost',
port: 6379,
}),],
controllers: [ProductsController],
providers: [ProductsService],
exports: [ProductsService],
})
export class ProductModule {}
products.controller.ts
import {
Body,
CACHE_MANAGER,
Controller,
Delete,
Get,
Inject,
Param,
ParseIntPipe,
Patch,
Post,
UseGuards,
} from '@nestjs/common';
import { ProductsService } from './products.service';
@ApiTags('Products')
@Controller('products')
export class ProductsController {
constructor(
private readonly productService: ProductsService,
) { }
...
@Get('fromCache')
findAllWithRedis() {
return this.productService.findAllWithRedis();
}
...
products.service.ts
import { CACHE_MANAGER, Inject, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { ProductEntity } from './entities/product.entity';
import { Repository } from 'typeorm';
import { Cache } from 'cache-manager';
@Injectable()
export class ProductsService {
constructor(
@InjectRepository(ProductEntity) private productRepository: Repository<ProductEntity>,
@Inject(CACHE_MANAGER) private cacheManager: Cache) { }
...
// With redis v0.1
async findAllWithRedis() {
const cachedResult = await this.cacheManager.get('allProducts');
if (cachedResult) {
console.log(`result from Redis :D `)
return cachedResult;
}
const result = await this.productRepository.find();
await this.cacheManager.set('allProducts', result, 2)
console.log(`normal result`)
return result;
}
...
Reference
- https://velog.io/@haron/NestJS-Redis-%EC%A0%81%EC%9A%A9%ED%95%98%EA%B8%B0
- https://velog.io/@chuyong/Nest.js-redis-%EC%BA%90%EC%8B%9C-%EC%82%AC%EC%9A%A9%ED%95%98%EA%B8%B0
- https://medium.com/zigbang/nestjs%EC%9D%98-module%EA%B3%BC-cachemodule%EC%9D%84-%ED%99%9C%EC%9A%A9%ED%95%9C-redis-%EC%97%B0%EB%8F%99-2166a771196
728x90
'Research > Database' 카테고리의 다른 글
Postgres_쿼리 실행 계획 분석 (0) | 2023.03.07 |
---|---|
db_Redis 클라우드 사용하는 방법 (0) | 2023.03.01 |
DB_Redis 설치 및 명령어 Cheatsheet(Mac OS) (0) | 2023.02.27 |
DB의 인덱스란 (0) | 2023.02.26 |
DB_Optimistic Lock vs. Pessimistic Lock (0) | 2023.02.24 |
댓글