스프링

[Spring] 스프링부트 RabbitMQ 연동하기

nan2 2023. 6. 14. 10:32
반응형

 

도커를 이용하여 RabbitMQ 서버가 구성되었다고 가정하고 시작함

아래 글 참조

2023.05.31 - [docker] - [docker] rabbitmq 설치 및 사용법

 

의존성 추가

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-amqp'
    implementation 'com.fasterxml.jackson.core:jackson-databind'
}

 

 

application.yml 파일에 설정 정보 입력

spring:
  rabbitmq:
    host: 접속할 서버 IP 주소
    port: 접속할 포트 (default: 5672)
    username: RabbitMQ 유저 아이디
    password: RabbitMQ 유저 비밀번호
    virtual-host: virtual host를 사용하는 경우 virtual host 이름

 

Message Listener (RabbitMQ 의 큐에서 메시지를 받아옴)

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

@Service
public class Receiver {

    @RabbitListener(queues = "spring-boot")
    public void receiveMessage(final Message message) {
        System.out.println(message);
    }

}

 

Message Listener Configuration

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@SpringBootApplication
public class MessageRabbitmqApplication {

    private static final String topicExchangeName = "spring-boot-exchange";
    private static final String queueName = "spring-boot";

    @Bean
    Queue queue() {
        return new Queue(queueName, false);
    }

    @Bean
    TopicExchange exchange() {
        return new TopicExchange(topicExchangeName);
    }

    @Bean
    Binding binding(Queue queue, TopicExchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with("foo.bar.#");
    }
    
    @Bean
    SimpleMessageListenerContainer container (ConnectionFactory connectionFactory,
    										MessageListenerAdapter listenerAdapter) {
    	SimpleMessageListenerContainer continer = new SimpleMessageListenerContainer();
        container.setConnectionFactory = connectionFactory;
        container.setQueueNames = queueName;
        container.setMessageListener(listenerAdapter);
        return container;
    }

    @Bean
    MessageListenerAdapter listenerAdapter() {
        return new MessageListenerAdapter(receiver, "receiveMessage");
    }
    
    public static void main (String[] args) throws InterruptedException {
    	SpringApplication.run(MessageRabbitmqApplication.class. agrs).clse();
    }

}
  • Queue : 지정된 이름으로 Queue를 생성 및 등록함. 서로 다른 이름으로 여러개의 Queue를 등록할 수도 있다.
  • Exchange : Exchange 설정함. TopicExchange를 사용해 주어진 패턴과 일치하는 Queue에 메시지를 전달한다. 설정할 수 있는 Exchange에는 Direct, Fanout, Topic, Headers가 있다.
  • Binding : Exchange가 Queue에게 메시지를 전달하기 위한 룰. 빈으로 등록한 Queue와 Exchange를 바인딩하면서 Exchange에서 사용될 패턴을 설정해 주었다.
  • SimpleMessageListenerContainer: SimpleMessageListenerContainer 에 MessageListener 와 queue name, ConnectionFactory 를 넣어 컨테이너를 만들어준다.

 

테스트하기

@Component
public class Runner implements CommandLineRunner {
	private final RabbitTemplate rabbitTemplate;
    private final Receiver receiver;
    
    public Runner (Receiver receiver, RabbitTemplate rabbitTemplate) {
    	this.receiver = receiver;
        this.rabbitTemplate = rabbitTemplate;
    }
    
    @Override
    public void run (String ... args) throws Exception {
    	System.out.println("Sending Message... ");
        rabbitTemplate.convertAndSend(MessageRabbitmqApplication.topicExchangeName, "foo.bar.baz", "Hello from RabbitMQ!");
    }
}

 

 

출처: 

https://spring.io/guides/gs/messaging-rabbitmq/

반응형