[Spring Boot] RabbitMQ에 대해서 알아보자

KUKJIN LEE's profile picture

KUKJIN LEE1개월 전 작성

쉽게 설명하기 위해 예를 들자면, 회사에서 A가 B에게 문서를 전달할 때, A가 직접 B에게 전달하는 것이 아니라 중앙 우편실에 A가 문서를 맡기고, B는 문서가 필요할 때 중앙 우편실에 방문해 정보를 얻는것이다.

rabbitMq

RabbitMQ란?

RabbitMQ는 AMQP(Advanced Message Queuing Protocol)를 구현한 오픈소스 메시지 브로커입니다. 다양한 언어와 플랫폼을 지원하며, 높은 신뢰성과 유연한 라우팅, 메시지 저장 기능을 제공합니다. RabbitMQ는 큐, 익스체인지(Exchange), 바인딩(Binding) 등 AMQP 표준 개념을 사용해 메시지를 효율적으로 라우팅하고 처리합니다.

 

구조 개요

  • 생산자(Producer): RabbitTemplate를 통해 메시지를 익스체인지로 보냅니다.

  • 익스체인지(Exchange): 라우팅 키(Routing Key)와 바인딩을 통해 메시지를 적절한 큐로 라우팅합니다.

  • 큐(Queue): 메시지가 도착하면, 큐에 바인딩된 소비자가 메시지를 꺼내 처리합니다.

  • 소비자(Consumer): @RabbitListener나 MessageListenerContainer를 통해 메시지를 비동기적으로 수신하고 처리합니다.

 

Exchange, Queue, Binding 설정 클래스

@Bean 메서드로 Exchange, Queue, Binding을 생성한다.

package com.example.amqp;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AmqpConfig {
  @Bean
  public DirectExchange exchange() {
    return new DirectExchange("product.exchange");
  }
  @Bean
  public Queue queue() {
    return new Queue("product.created.queue", true);
  }
  @Bean
  public Binding binding(Queue queue, DirectExchange exchange) {
    return BindingBuilder.bind(queue).to(exchange).with("product.created");
  }
}

메시지 전송(생산자) 구현

RabbitTemplate를 주입받아 메시지를 전송합니다.

package com.example.amqp;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;
import java.util.UUID;

@Service
public class ProductService {
  private final RabbitTemplate rabbitTemplate;
  public ProductService(RabbitTemplate rabbitTemplate) {
    this.rabbitTemplate = rabbitTemplate;
  }
  public void createProduct(String name) {
    Product product = new Product();
    product.setId(UUID.randomUUID().toString());
    product.setName(name);
    rabbitTemplate.convertAndSend("product.exchange", "product.created", product);
  }
}

메시지 수신 구현

@RabbitListener를 사용해 큐로부터 메시지를 수신합니다.

package com.example.amqp;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

@Service
public class ProductConsumer {
  @RabbitListener(queues = "product.created.queue")
  public void handleProductCreated(Product product) {
    System.out.println("Received product: " + product.getId() + " " + product.getName());
  }
}

비동기 메시징 아키텍처를 구현하면, 시스템 확장성, 유연성, 장애 내성을 강화할 수 있습니다. 직관적 API와 어노테이션을 활용하면 복잡한 설정 작업을 단순화하고 생산성과 유지보수성을 높일 수 있습니다.

New Tech Posts