[Message Queue] Connection 하나에서 Channel을 여러개를 두자

김태훈·2024년 4월 4일
0

성균관대 Skkuding

목록 보기
12/15
@Injectable()
export class SubmissionService implements OnModuleInit {
  private readonly logger = new Logger(SubmissionService.name)

  constructor(
    private readonly prisma: PrismaService,
    private readonly amqpConnection: AmqpConnection,
    private readonly configService: ConfigService,
    private readonly httpService: HttpService,
    private readonly traceService: TraceService
  ) {}
  onModuleInit() {
    this.amqpConnection.createSubscriber(
      async (msg: object) => {
        try {
          const res = await this.validateJudgerResponse(msg)
          await this.handleJudgerMessage(res)
        } catch (error) {
          if (
            Array.isArray(error) &&
            error.every((e) => e instanceof ValidationError)
          ) {
            this.logger.error(error, 'Message format error')
          } else if (error instanceof UnprocessableDataException) {
            this.logger.error(error, 'Iris exception')
          } else {
            this.logger.error(error, 'Unexpected error')
          }
          return new Nack()
        }
      },
      {
        exchange: EXCHANGE,
        routingKey: RESULT_KEY,
        queue: RESULT_QUEUE,
        queueOptions: {
          channel: CONSUME_CHANNEL
        }
      },
      ORIGIN_HANDLER_NAME
    )
  }

onModuleInit는 NestJS에서 모듈이 초기화될 때 호출되는 함수로, 이를 통해 하나의 Connection만 만든다. 그 이후, 연결된 amqpConnection을 사용하여

this.amqpConnection.publish(EXCHANGE, SUBMISSION_KEY, judgeRequest, {
    messageId: String(submission.id),
    persistent: true,
    type: PUBLISH_TYPE
})

이런식으로 publish까지 한다. 따라서 모듈 초기화 시 맺었던 하나의 Connection에서 통신이 이루어진다.

싱글톤처럼 사용된다는 뜻이다.

profile
기록하고, 공유합시다

0개의 댓글