![]() |
VOOZH | about |
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).
Before you begin, make sure you have the following tools and dependencies installed:
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:
In the code shown above:
Step 5: Creating a RabbitMQ Consumer
To consume messages from RabbitMQ, we will create a consumer. Here's an example consumer class.
In this code:
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:
In this configuration class:
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:
This is how we complete configuration of RabbitMQ on spring boot app with Spring AMQP.