RabbitMQ + Spring Boot Example

Learner, Love to make things simple, Full Stack Developer, StackOverflower, Passionate about using machine learning, deep learning and AI
Search for a command to run...

Learner, Love to make things simple, Full Stack Developer, StackOverflower, Passionate about using machine learning, deep learning and AI
No comments yet. Be the first to comment.
Spring Boot tutorials, java and spring cloud tutorials where we can cover other parts like microservices, etc.
When using Spring Data JPA, developers can use derived query methods to generate queries based on the name of the method. This approach eliminates the need for manually writing queries, reducing boilerplate code and increasing productivity. Derived q...
Move beyond traditional RESTful thinking. Learn how to design APIs specifically for MCP (Model Context Protocol) servers. This guide covers the shift in mindset, a practical OpenAPI 3.1 example, and a Spring Boot implementation to make your services ...

Extending Kestra to Every Corner of Your Data Stack. Introduction: The Power of Plugins Imagine you're a master chef. You don't just have one knife - you have specialized tools for every task: a paring knife for delicate work, a chef's knife for chop...
Mastering Complex Orchestration Scenarios. Introduction: The Orchestrator's Toolkit Imagine you're conducting a symphony. You don't just wave your baton - you cue sections, adjust tempo, handle surprises, and ensure harmony. That's what advanced work...
From Data Extraction to Loading - A Practical Guide Introduction: Why ETL Still Matters in the Modern Data Stack Remember when data engineering was "extract, transform, load"? Some say ETL is dead, replaced by ELT, reverse ETL, and data mesh. But her...
Building Blocks of Declarative Orchestration. Introduction: The Power of Simplicity Imagine trying to build a house without understanding bricks, beams, and blueprints. That's what using an orchestration tool without understanding its core concepts f...
Message Queues are used to handle the communication between different systems in a distributed environment. RabbitMQ is one of the most widely used message brokers. It is an open-source message broker that implements the Advanced Message Queuing Protocol (AMQP). Spring Boot is a popular Java framework that provides an easy way to build production-grade Spring-based applications. In this tutorial, we will look at how to use RabbitMQ with Spring Boot.
Java 11 or higher
RabbitMQ installed and running locally
To install RabbitMQ, follow the instructions for your operating system on the official website https://www.rabbitmq.com/download.html.
After installing RabbitMQ, start the RabbitMQ server by running the following command in your terminal or command prompt:
rabbitmq-server
By default, RabbitMQ runs on port 5672. You can access the RabbitMQ management console at http://localhost:15672 with the default credentials guest/guest.
The easiest way to create a new Spring Boot project is by using the Spring Initializr. Go to https://start.spring.io/ and configure your project as follows:
Project type: Maven or Gradle
Language: Java
Spring Boot: Latest version
Group: com.example
Artifact: rabbitmq-example
Dependencies: Web, AMQP
Click the Generate button to download the project. Import the project into your IDE of choice.
To integrate RabbitMQ with Spring Boot, we need to add the following dependencies to our pom.xml or build.gradle file:
<!-- pom.xml -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
// build.gradle
implementation 'org.springframework.boot:spring-boot-starter-amqp'
In your Spring Boot application, you need to configure the connection details for RabbitMQ. This can be done using properties in the application.properties file.
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
Next, we need to create a queue to which messages can be sent. This can be done using the Queue class in the org.springframework.amqp.core package.
@Configuration
public class RabbitMQConfig {
@Bean
public Queue queue() {
return new Queue("myQueue", false);
}
}
In this section, we will implement an example application that sends and receives messages using RabbitMQ.
First, we need to configure the connection to the RabbitMQ instance. Create a new configuration class called RabbitMQConfig in the com.example.rabbitmqexample.config package and add the following code:
@Configuration
public class RabbitMQConfig {
@Value("${spring.rabbitmq.host}")
private String host;
@Value("${spring.rabbitmq.port}")
private int port;
@Value("${spring.rabbitmq.username}")
private String username;
@Value("${spring.rabbitmq.password}")
private String password;
@Bean
public ConnectionFactory connectionFactory() {
CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
connectionFactory.setHost(host);
connectionFactory.setPort(port);
connectionFactory.setUsername(username);
connectionFactory.setPassword(password);
return connectionFactory;
}
@Bean
public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
return new RabbitTemplate(connectionFactory);
}
@Bean
public Queue exampleQueue() {
return new Queue("example.queue", true);
}
}
This configuration class defines the RabbitMQ connection parameters and creates a RabbitTemplate bean, which provides us with a simple API for sending messages to RabbitMQ. It also defines a Queue bean, which represents the message queue that we will use in our example application.
To send a message to the queue, we can use the RabbitTemplate class in the org.springframework.amqp.rabbit.core package.
@RestController
public class RabbitMQController {
@Autowired
private RabbitTemplate rabbitTemplate;
@Autowired
private Queue queue;
@GetMapping("/sendMessage")
public String sendMessage() {
String message = "Hello RabbitMQ!";
rabbitTemplate.convertAndSend(queue.getName(), message);
return "Message sent to the RabbitMQ Successfully";
}
}
To receive messages from the queue, we can use the @RabbitListener annotation on a method in a Spring Bean.
@Component
public class RabbitMQListener {
@RabbitListener(queues = "myQueue")
public void processMessage(String message) {
System.out.println("Received Message: " + message);
}
}
Start the RabbitMQ server and run the Spring Boot application. To send a message, navigate to http://localhost:8080/sendMessage. The message will be added to the queue, and the RabbitMQListener will receive and print the message.
In this tutorial, we looked at how to use RabbitMQ with Spring Boot. We covered the basics of sending and receiving messages, and how to configure the connection details for RabbitMQ in a Spring Boot application. With this knowledge, you should be able to start using RabbitMQ in your own Spring Boot applications.
I hope this helps, you!!
More such articles:
https://www.youtube.com/channel/UCiTaHm1AYqMS4F4L9zyO7qA
\==========================**=========================
If this article adds any value to you then please clap and comment.
Let’s connect on Stackoverflow, LinkedIn, & Twitter.