Spring Boot + RabbitMQ (2023) Hello World Example | CodeUsingJava






















Spring Boot + RabbitMQ (2023) Hello World Example

In this tutorial we will be implementing a RabbitMq with Spring boot with the help of a simple example.
RabbitMq is a AMQP broker that is used widely. AMQP stands for Advanced Message Queuing Protocol. RabbitMq is use for sending as well as receiving messages.
Different programming languages as well operating systems support RabbitMq.
The basic flow of RabbitMQ can be expressed as follows-
Spring BootRabbitMQ
The Exchange method helps in the routing of messages to zero or more queues. In our example there are two microservices Sender and Receiver,
RabbitMq acts as a middleman for the sender and the receiver.The sender will generate a message and then send the message to the messaging queue.The Receiver then connects to the broker and now the message can be seen by the Receiver.

The digrammatic representation of RabbitMq in our example can be shown in the following manner:-
Spring BootRabbitMQ

Installation of RabbitMq

For downloading the RabbitMQ, firstly we need to download Erlang and install the binary file successfully.
Now we need to download RabbitMQ and then install RabbitMQ on our system.
Open Command Prompt and go to the location where RabbitMQ is installed and start the server by the following command:-
rabbitmq-server start
Spring BootRabbitMQ server start

install all the plugins using the following command:-
rabbitmq-plugins.bat enable rabbitmq_management
Spring BootRabbitMQ plugin
  • Project Structure

    This will be the standard directory layout for maven project structure-
    Spring BootRabbitMQ plugin
    We need to start by creating a Maven pom.xml(Project Object Model) file. The pom.xml file contains the project configuration details.
    	<project xmlns="http://maven.apache.org/POM/4.0.0"
    	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    	<modelVersion>4.0.0</modelVersion>
    
    	<groupId>com.codeusingjava</groupId>
    	<artifactId>SpringBootRabbitMQ</artifactId>
    	<version>0.0.1-SNAPSHOT</version>
    
    	<parent>
    		<groupId>org.springframework.boot</groupId>
    		<artifactId>spring-boot-starter-parent</artifactId>
    		<version>2.3.2.RELEASE</version>
    	</parent>
    
    	<properties>
    		<java.version>1.8</java.version>
    	</properties>
    
    	<dependencies>
    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter-web</artifactId>
    		</dependency>
    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter-amqp</artifactId>
    		</dependency>
    	</dependencies>
    
    	<build>
    		<plugins>
    			<plugin>
    				<groupId>org.springframework.boot</groupId>
    				<artifactId>spring-boot-maven-plugin</artifactId>
    			</plugin>
    		</plugins>
    
    		<finalName>Spring-Boot-Rabbitmq</finalName>
    	</build>
    </project>
    
    Create the application.properties class for the configuration. All the configurations related to RabbitMQ are also done in this file.
    	spring.application.name=SpringbootRabbitMQ
    	server.port=8889
    	
    	spring.rabbitmq.host=localhost
    	spring.rabbitmq.port=5672
    	spring.rabbitmq.username=guest
    	spring.rabbitmq.password=guest
    	rabbitmq.queue=MessageQueue
    	rabbitmq.exchange=exchange
    	rabbitmq.routingkey=routekey
    
    The configuration class is as follows-
    The topicExchange is responsible for matching between the routing key and the pattern.
    With the help of binding, we can set up relation between queue and an exchange.
    	package com.codeusingjava.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.beans.factory.annotation.Value;
    	import org.springframework.context.annotation.Bean;
    	import org.springframework.context.annotation.Configuration;
    	
    	@Configuration
    	public class RabbitMqConfig {
    	
    		
    		@Value("")
    		private String qName;
    		
    		
    		@Value("")
    		private String exchange;
    		
    		
    		@Value("")
    		private String routingKey;
    	
    		@Bean
    		Queue qu() {
    			return new Queue(qName, Boolean.FALSE);
    		}
    	
    		@Bean
    		TopicExchange topicExchange() {
    			return new TopicExchange(exchange);
    		}
    	
    		@Bean
    		Binding binding(final Queue q, final TopicExchange topicExchange) {
    			return BindingBuilder.bind(q).to(topicExchange).with(routingKey);
    		}
    	}
    	
    
    The controller class is as follows- @ResponseStatus annotation is used to organize with a status code which we can apply to the HttpResponse.
    	package com.codeusingjava.sender.controller;
    
    	import org.slf4j.Logger;
    	import org.slf4j.LoggerFactory;
    	import org.springframework.amqp.core.Binding;
    	import org.springframework.amqp.rabbit.core.RabbitTemplate;
    	import org.springframework.beans.factory.annotation.Autowired;
    	import org.springframework.http.HttpStatus;
    	import org.springframework.web.bind.annotation.GetMapping;
    	import org.springframework.web.bind.annotation.PathVariable;
    	import org.springframework.web.bind.annotation.ResponseStatus;
    	import org.springframework.web.bind.annotation.RestController;
    	
    	
    	@RestController
    	public class Sender {
    	
    		private static final Logger LOGGER = LoggerFactory.getLogger(Sender.class);
    	
    
    		@Autowired
    		RabbitTemplate rabbitTemplate;
    		@Autowired
    		Binding binding;
    	
    		@GetMapping(value = "/send/{msg}")
    		@ResponseStatus(code = HttpStatus.OK)
    		public String send(@PathVariable("msg") final String message) {
    			LOGGER.info("Sending message to the queue.");
    			rabbitTemplate.convertAndSend(binding.getExchange(), binding.getRoutingKey(), message);
    			LOGGER.info("Message sent successfully to the queue!!!");
    			return "Great!! your message is sent";
    		}
    	}
    	
    
    The Receiver class will first read the name of the queue from the Queue Object and then logger will be printed which will contain the messages also.
    	package com.codeusingjava.receiver;
    
    	import org.slf4j.Logger;
    	import org.slf4j.LoggerFactory;
    	import org.springframework.amqp.core.Queue;
    	import org.springframework.amqp.rabbit.annotation.RabbitListener;
    	import org.springframework.beans.factory.annotation.Autowired;
    	import org.springframework.stereotype.Component;
    	
    	@Component
    	public class Receiver {
    	
    		private static final Logger LOGGER = LoggerFactory.getLogger(Receiver.class);
    	
    		@Autowired
    		Queue qu;
    	
    		@RabbitListener(queues = "#{qu.getName()}")	
    		public void getMsg(final String message) {
    			LOGGER.info("Getting messages.....");
    			LOGGER.info("Finally Receiver received the message and the message  is..\n" + message);
    		}
    	}
    	
    
    The main class for the SpringbootRabbitMQ application is as follows:-
    	package com.codeusingjava;
    
    	import org.slf4j.Logger;
    	import org.slf4j.LoggerFactory;
    	import org.springframework.boot.SpringApplication;
    	import org.springframework.boot.autoconfigure.SpringBootApplication;
    	
    	
    	@SpringBootApplication
    	public class SpringbootRabbitmq {
    		
    		public static void main(String[] args) {
    			SpringApplication.run(SpringbootRabbitmq.class, args);
    			
    		}
    	}
    	
    
If we now run the application we get the output as follows
output

url

Now we see the console logs. This logs are from the Receiver side.
console output
Type the url http://localhost:15672/#/queues
rabvbbitmq console output

Downloads-

Spring Boot + RabbitMQ Example