Using RabbitMQ with Spring Boot

RabbitMQ is one of the most popular open-source message brokers, and it enables communication between different components of a distributed system. It works by accepting, storing, and forwarding messages to consumers in an asynchronous, decoupled manner, making it ideal for use in microservices architectures or systems requiring high scalability and reliability.

In this post, we will explore how to integrate RabbitMQ with Spring Boot, one of the most widely-used frameworks for building Java-based applications. By the end, you will be able to send and receive messages between producers and consumers in your Spring Boot application using RabbitMQ.

Prerequisites

  1. Java 8 or higher
  2. Spring Boot 2.x or higher
  3. RabbitMQ installed locally or hosted (you can also use services like CloudAMQP for hosted RabbitMQ).
  4. Maven

Step 1: Setting Up RabbitMQ

If you don't have RabbitMQ set up yet, you can install it locally. For installation, visit the official RabbitMQ website or use Docker to quickly spin up a RabbitMQ instance. To run RabbitMQ using Docker, execute the following:

docker run -d --name rabbitmq -p 5672:5672 -p 15672:15672 rabbitmq:management        

This command will run RabbitMQ with the management plugin enabled (accessible via https://localhost:15672).

Step 2: Add Dependencies in Spring Boot Project

In your pom.xml (Maven), add the following dependencies:

<dependencies>
    <!-- Spring Boot Web dependency -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <!-- Spring Boot AMQP (RabbitMQ) dependency -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-amqp</artifactId>
    </dependency>
    
    <!-- Spring Boot starter test (optional for testing) -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>        

Step 3: Configure RabbitMQ Connection in application.properties

Now, configure the RabbitMQ connection details in the src/main/resources/application.properties file:

# RabbitMQ configuration
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
spring.rabbitmq.virtual-host=/        

These properties tell Spring Boot where RabbitMQ is running (by default on localhost), along with the credentials (which are guest by default).

Step 4: Define a Queue, Exchange, and Binding

In RabbitMQ, you need to define a Queue to store messages, an Exchange to route messages, and a Binding that connects the Queue to the Exchange. You can do all of this in your Spring Boot application.

Create a configuration class to set up these RabbitMQ components:

package com.example.rabbitmq.config;

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.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitMQConfig {

    public static final String QUEUE_NAME = "hello-queue";
    public static final String EXCHANGE_NAME = "hello-exchange";
    public static final String ROUTING_KEY = "hello.key";

    @Bean
    public Queue queue() {
        return new Queue(QUEUE_NAME, false);  // non-durable queue
    }

    @Bean
    public TopicExchange exchange() {
        return new TopicExchange(EXCHANGE_NAME);
    }

    @Bean
    public Binding binding() {
        return BindingBuilder.bind(queue()).to(exchange()).with(ROUTING_KEY);
    }
}        

Here, we define:

  • A queue called hello-queue
  • An exchange called hello-exchange
  • A routing key hello.key, which binds the queue and exchange.

Step 5: Create a Producer to Send Messages

The producer will send messages to the RabbitMQ exchange, which then routes them to the bound queue. Let’s create a simple producer that sends a message to the queue.

package com.example.rabbitmq.sender;

import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class MessageSender {

    @Autowired
    private AmqpTemplate amqpTemplate;

    public void sendMessage(String message) {
        amqpTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME, RabbitMQConfig.ROUTING_KEY, message);
        System.out.println("Sent: " + message);
    }
}        

In the code above:

  • The AmqpTemplate is used to send messages to RabbitMQ.
  • We use convertAndSend to send the message to the exchange with the specified routing key.

Step 6: Create a Consumer to Receive Messages

Now, we need to define a consumer that will listen for messages on the queue.

package com.example.rabbitmq.receiver;

import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

@Service
public class MessageReceiver {

    @RabbitListener(queues = RabbitMQConfig.QUEUE_NAME)
    public void receiveMessage(String message) {
        System.out.println("Received: " + message);
    }
}        

In the above code:

  • The @RabbitListener annotation tells Spring Boot to listen for messages on the specified queue (hello-queue).
  • The receiveMessage method is invoked when a message is received.

Step 7: Create a Controller to Trigger the Message Send

Let’s create a simple REST controller to trigger the sending of messages via an HTTP request.

package com.example.rabbitmq.controller;

import com.example.rabbitmq.sender.MessageSender;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MessageController {

    @Autowired
    private MessageSender messageSender;

    @GetMapping("/send")
    public String sendMessage(@RequestParam("message") String message) {
        messageSender.sendMessage(message);
        return "Message sent: " + message;
    }
}        

Step 8: Run the Application

Now that everything is set up, you can run your Spring Boot application. If you're using Maven, you can run the following:

mvn spring-boot:run        

Once the application is up and running, you can test it by visiting:

https://localhost:8080/send?message=HelloRabbitMQ        

You should see the message printed in the console of both the producer (sending the message) and the consumer (receiving the message).

Conclusion

With just a few lines of code, you have successfully integrated RabbitMQ into a Spring Boot application. This setup enables you to send and receive messages asynchronously using RabbitMQ, which is highly scalable and reliable. RabbitMQ is widely used in microservices and event-driven systems where components need to communicate without being tightly coupled.

As you continue to develop, you may want to explore advanced topics such as message durability, message acknowledgment, and error handling to build a more resilient and production-ready messaging system.

Happy coding!

Lucas Wolff

.NET Developer | C# | TDD | Angular | Azure | SQL

3 个月

Very interesting!

回复

Excellent, thanks for sharing!!

回复
Mauro Marins

Senior .NET Software Engineer | Senior Full Stack Developer | C# | .Net Framework | Azure | React | SQL | Microservices

3 个月

Great content, thanks for sharing!

回复
Rodrigo Tenório

Senior Software Engineer | Java | Spring | AWS

3 个月

Good point!

回复
Otávio Prado

Senior Business Analyst | ITIL | Communication | Problem-Solving | Critical Thinking | Data Analysis and Visualization | Documentation | BPM | Time Management | Agile | Jira | Requirements Gathering | Scrum

3 个月

Great advice! Thanks for sharing JUNIOR NAKAMURA ! ????

回复

要查看或添加评论,请登录

JUNIOR N.的更多文章

社区洞察

其他会员也浏览了