Event-Driven MicroServices using SpringBoot and RabbitMQ
Project Achitecture
- RabbitMQ Producer: Order service
- RabbitMQ Consumer:
- Stock service:
- Email service:
Create and Setup Microservices
access spring initializr, each microservice needs install plugins:
- Spring for RabbitMQ
- Spring Web
- Lombok
configure the port:
- Order service: 8080(default)
- Stock service: 8081
- Email service: 8082
// filepath: stock-service/src/main/resources/application.properties
server.port=8081
// filepath: email-service/src/main/resources/application.properties
server.port=8082
RabbitMQ Producer – Order Service
Configure RabbitMQ step by step
- configure the basic variables for avoiding the hard coding.
// order-service/src/main/resources/application.properties
rabbitmq.queue.order.name=order
rabbitmq.exchange.name=order_exchange
rabbitmq.binding.routing.key=order_routing_key
- create config package and RabbitMQConfig to auto create queue, exchange, routing-key binding and redefint the converter(support json).
// order-service/src/main/java/com/example/orderservice/config/RabbitMQConfig.java
package com.example.orderservice.config;
import org.springframework.amqp.core.*;
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.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RabbitMQConfig {
// @Value is a Spring Boot annotation used for injecting values into variables
@Value("${rabbitmq.queue.order.name}")
String queueName;
@Value("${rabbitmq.exchange.name}")
String exchangeName;
@Value("${rabbitmq.binding.routing.key}")
String routingKey;
// spring bean for queue -- order queue
// @Bean is an annotation in Spring Boot used to declare a method that returns an object to be managed by the Spring container as a bean.
// The method is used to tell the container how to create the bean instance, and the returned object is registered with the container for use throughout the program.
@Bean
public Queue orderQueue(){
return new Queue(queueName);
}
// spring bean for exchange
@Bean
public TopicExchange orderExchange(){
return new TopicExchange(exchangeName);
}
// spring bean for binding between exchange and queue using routing key
@Bean
public Binding binding(){
return BindingBuilder
.bind(orderQueue())
.to(orderExchange())
.with(routingKey);
}
// message converter
@Bean
public MessageConverter converter(){
return new Jackson2JsonMessageConverter();
}
// configure RabbitMQTemplate
@Bean
public AmqpTemplate amqpTemplate(ConnectionFactory connectionFactory){
RabbitTemplate rabbitTemplate = new R