Spring Boot - RabbitMQ Configuration
Last Updated :
04 Jan, 2025
The RabbitMQ is a scalable and commonly used message queue for exchanging messages among different parts of applications or between multiple applications. Both Spring Boot and Spring AMQP provide great integration capabilities with RabbitMQ within the world of Java Dev. In this article, we’ll go through the steps to set up RabbitMQ with a Spring Boot app (using Spring AMQP).
Prerequisites
Before you begin, make sure you have the following tools and dependencies installed:
- Java JDK (8 or higher)
- Spring Boot
- RabbitMQ Server (installed and running)
Step-by-Step Implementation
Now let's move to our main steps:
Step 1: Creating a Spring Boot Project
If you don't have an existing Spring Boot project, you can create one using spring initializr (https: //start.spring.io/). When building your project, add this “AMQP” dependency in the pom.xml.
Step 2: Adding Dependencies
If you are on Spring boot then you need to add the following dependency to your pom.xml file (mvn) to consume Rabbit MQ with Spring BOOT framework as shown below.
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
</dependencies>
Step 3: Configuring RabbitMQ Connection
Within your Spring Boot project you have to configure the RabbitMQ connection details. Create a application.properties file in your project's src/main/resources directory and add the following properties:
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=username
spring.rabbitmq.password=password
Another way is to add a application.yml file in the same src/main/resources directory and add the following properties:
spring:
rabbitmq:
host:localhost
port:5672
username:username
password:password
Replace ''username'' and ''password'' with your RabbitMQ server credentials.
Step 4: Creating a RabbitMQ Producer
Now Let’s create a RabbitMQ producer that publishes messages to the given RabbitMQ exchange. We can define a simple class like this:
Java
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class RabbitMQProducer {
@Autowired private RabbitTemplate rabbitTemplate;
public void sendMessage(String message)
{
rabbitTemplate.convertAndSend(
"exchange-name", "routing-key", message);
}
}
In the code shown above:
- We inject the RabbitTemplate class which is a Spring AMQP class that simplifies message publishing.
- The "sendMessage" method sends a message to the specified exchange with a given routing key.
Step 5: Creating a RabbitMQ Consumer
To consume messages from RabbitMQ, we will create a consumer. Here's an example consumer class.
Java
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
@Component
public class RabbitMQConsumer {
@RabbitListener(queues = "queue-name")
public void receiveMessage(String message)
{
// Handle the received message here
System.out.println("Received message: " + message);
}
}
In this code:
- We annotate the receiveMessage method with @RabbitListener to specify the queue from which to consume messages.
- When a message is received, the ""receiveMessage" method will be invoked and the consumer can continue processing the consumed message.
Step 6: Configuring Exchange and Queue
To make this work, we have to configure the RabbitMQ exchange and queue. We can do this by adding a configuration class:
Java
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Exchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RabbitMQConfig {
@Bean public Queue queue()
{
return new Queue("queue-name", false);
}
@Bean public Exchange exchange()
{
return new DirectExchange("exchange-name");
}
@Bean
public Binding binding(Queue queue, Exchange exchange)
{
return BindingBuilder.bind(queue)
.to(exchange)
.with("routing-key")
.noargs();
}
}
In this configuration class:
- We create the following function to define a “queue-name”.
- We create a straight exchange called “exchange-name”.
- And we bind the queue <queue_name> and exchange <exchange_name> with the routing key “routing_key”.
Once we have our producer, consumer, and configuration all set up, we can start sending and receiving messages with RabbitMQ in our Spring Boot app. Here's how we can use the producer:
Java
@Autowired private RabbitMQProducer rabbitMQProducer;
// Sending a message
rabbitMQProducer.sendMessage("connected to RabbitMQ!");
This is how we complete configuration of RabbitMQ on spring boot app with Spring AMQP.
Similar Reads
Spring Boot - Externalized Configuration
In Spring Boot, externalized configuration is a feature that allows you to separate configuration settings from your code. This means you can change how your application behaves by modifying configuration files without needing to recompile or redeploy the application. Spring Boot supports various co
4 min read
Spring Boot Security Auto-Configuration
Spring Boot Security Auto Configuration can simplify the process of securing the Spring Boot applications by providing default security configurations. It can automate the many common security tasks such as setting up the authentication, and authorization and it can handle the common security vulner
4 min read
Spring Boot - Auto-configuration
Spring Boot is heavily attracting developers toward it because of three main features as follows: Auto-configuration - such as checking for the dependencies, the presence of certain classes in the classpath, the existence of a bean, or the activation of some property.An opinionated approach to confi
5 min read
Spring Boot - @ConfigurationProperties
In Spring Boot, @ConfigurationProperties Annotation allows the developer to map the entire content of the properties file to a POJO (Plain Old Java Object). A property file can be either application.properties or application.yml. This annotation is useful when we have a large set of explicit configu
6 min read
Spring Boot - Cloud Configuration Server
In microservices, we have several different services responsible for different functionalities. These services act like smaller application modules, which together form the application. Each of these modules has its own responsibility, based on the business logic of the application being built. Thes
10 min read
Spring Boot - Create a Custom Auto-Configuration
Usually, we might be taking a maven project or grade project for Spring Boot related projects. We will be adding the dependencies in pom.xml (in case of a maven project). In a spring application, Spring Boot auto-configuration helps to automatically configure by checking with the jar dependencies th
4 min read
Spring Boot - Configuring a Main Class
Spring Boot simplifies the process of creating and running Java applications by providing a set of conventions and auto configurations. The main class in the Spring Boot application acts as the entry point where the application starts the execution. It is responsible for bootstrapping the Spring con
4 min read
SpringBoot Configuration
Spring Boot is a powerful framework built on top of the Spring framework. Spring Boot allowed programmers to focus mainly on the business logic without worrying about the external configuration and setting up the environment resources like server setup. Configuration of SpringBootConfiguration is th
9 min read
Spring Boot - Internationalization
Before understanding Spring Boot-Internationalization, we must know what internalization in general means. Internationalization is an action or process of making something international which means making things adaptable or available everywhere. In this article, we will be discussing Internationali
6 min read
Spring Boot - Integration with Kafka
Apache Kafka is a distributed messaging system designed for high-throughput and low-latency message delivery. It is widely used in real-time data pipelines, streaming analytics, and other applications requiring reliable and scalable data processing. Kafkaâs publish-subscribe model allows producers t
7 min read