CloudAMQP - RabbitMQ as a Service
CloudAMQP - industry leading RabbitMQ as a service Start your managed cluster today. CloudAMQP is 100% free to try.
www.cloudamqp.com
클라우드 rabbitMQ 사용
해당 port 1883 사용하면 안됨 디폴트 port 사용
application.yml 설정
Cloud rabbitMQ 사용하면 vhost 해줘야하고 default port는 5672
rabbitmq:
host: dingo.rmq.cloudamqp.com
username: ulnwlrwi
password: 1-xzf7tfUz4szUS4qny24D96CPTy5xDv
virtual-host: ulnwlrwi
# port: 5672
RabbitMQ config 파일
binding() 함수 중요
exchange랑 queue랑 routingKey("order") 묶음
#"exch" 교환소에 "order" routingKey에 메시지를 보내면 "spring-boot" 큐에서 receive 받으면 된다.
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;
@Configuration
public class RabbitConfiguration {
private static final String queueName = "spring-boot";
private static final String topicExchangeName = "exch";
@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("order");
}
@Bean
RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory,
MessageConverter messageConverter) {
RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
rabbitTemplate.setMessageConverter(messageConverter);
return rabbitTemplate;
}
@Bean
MessageConverter messageConverter() {
return new Jackson2JsonMessageConverter();
}
}
import com.fastcampus.order.dto.CreateShopDto;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/rabbit")
@RequiredArgsConstructor
public class RabbitController {
private final RabbitTemplate rabbitTemplate;
@GetMapping("/send/{message}")
public String sendMessage(@PathVariable String message) {
CreateShopDto createShopDto = new CreateShopDto();
createShopDto.setShopName("공차");
createShopDto.setShopAddress("서현");
rabbitTemplate.convertAndSend("exch","order", createShopDto);
return "ok";
}
@GetMapping("/receive")
public String recevieMessage() {
Message receive = rabbitTemplate.receive("spring-boot");
System.out.println(receive.getBody());
return receive.toString();
}
}
import com.fastcampus.order.dto.CreateShopDto;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.stereotype.Component;
@RequiredArgsConstructor
@Component
public class Consumer {
private final RabbitTemplate rabbitTemplate;
private final MessageConverter messageConverter;
@RabbitListener(queues = "spring-boot")
public void receiveMessage(final Message message) {
CreateShopDto createShopDto = (CreateShopDto) messageConverter.fromMessage(message);
System.out.println(createShopDto.getShopName());
System.out.println(createShopDto.getShopAddress());
}
}
[Consumer Config 파일 추가]
Producer에서 Consumer로 객체를 보낼때 객체의 패키지 경로가 다르면 에러가나서 Consumer에 패키지 경로로 수정해줘야한다.
// Producer에서 Consumer로 객체를 보낼때 객체의 패키지 경로가 다르면 에러가나서 Consumer에 패키지 경로로 수정해줘야한다.
@Bean(name = "rabbitListenerContainerFactory")
public SimpleRabbitListenerContainerFactory simpleRabbitListenerContainerFactory(
SimpleRabbitListenerContainerFactoryConfigurer configurer, ConnectionFactory connectionFactory) {
SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
configurer.configure(factory, connectionFactory);
factory.setAfterReceivePostProcessors(new MessagePostProcessor() {
@Override
public Message postProcessMessage(Message message) throws AmqpException {
String type = message.getMessageProperties().getHeaders().get("type").toString();
String typeId = null;
if (StringUtils.equalsIgnoreCase(type, "shop_create")) {
typeId = CreateShopDto.class.getName();
}
// else if (StringUtils.equalsIgnoreCase(type, "invoice.created")) {
// typeId = InvoiceCreatedMessage.class.getName();
// }
Optional.ofNullable(typeId).ifPresent(t -> message.getMessageProperties().setHeader("__TypeId__", t));
return message;
}
});
return factory;
}
https://minholee93.tistory.com/entry/RabbitMQ-Jackson2JsonMessageConvertor
[RabbitMQ] Jackson2JsonMessageConvertor
이번 글에서는 Spring Boot의 Jackson2JsonMessageConverter를 사용해 손쉽게 Object를 JSON Message Format으로 변경해보겠습니다. 1. Message Converter란? object를 rabbitmq의 message 형식으로 변환해주는 것..
minholee93.tistory.com
'백엔드 > Spring(Boot)' 카테고리의 다른 글
springboot h2 인메모리 모드 설정 (0) | 2022.06.30 |
---|---|
jpa @GeneratedValue (0) | 2022.04.16 |
Spring Gradle 빌드 (인텔리제이 방법 포함) (0) | 2022.04.10 |
SpringBoot Eureka 서버 설정 (0) | 2022.03.25 |
스프링 시큐리티 OAuth 2.0 (0) | 2022.03.17 |