[Nest.js] Redis MicroServices 구현하기 (1) - Subscribe

Woong·2023년 2월 6일
0

Nestjs

목록 보기
23/28

개요

  • 본 포스팅에선 cache 가 아닌 message pattern 을 이용한 Redis pub/sub 관점에서의 구현을 포스팅합니다.

사전 작업

  • redis 설치
  • 의존성 설치
    • yarn add ioredis @nestjs/microservices

Redis Subscribe 등록하기

  • main.tsMicroService 설정
import { NestFactory } from '@nestjs/core';
import { Transport } from '@nestjs/microservices'
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.connectMicroservice({

    transport: Transport.REDIS,
    options: {
      host: 'localhost',
      port: 6379,
    },
  });
  
  await app.startAllMicroservices();
  await app.listen(3001);
}
bootstrap();
  • AppModule 에 ClientsModule.register 로 등록
    • name 이 injection token 이 된다.
@Module({
  imports: [
    ClientsModule.register([
        {
          name: 'MY_SERVICE',
          transport: Transport.REDIS,
          options: {
            host: 'localhost',
            port: 6379,
          }
        },
      ]),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

Controller 설정

  • @MessagePatterns 데코레이터는 Controller 에서만 사용 가능하므로 주의
    • MessagePatternchannel 설정
@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @MessagePattern('notifications')
  getNotifications(@Payload() data: string[], @Ctx() context: RedisContext) {
      console.log(`Channel: ${context.getChannel()}`)
      console.log(`message : ${data}`)
  }
}

reference

0개의 댓글