RabbitMQ with Spring Boot

Its very easy to publish a message in RabbitMQ using spring boot.

Below is the code:

Create a spring boot starter project with below dependency

Pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<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>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.2.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.hk.rabbitmq</groupId>
    <artifactId>RabbitMQ</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>RabbitMQ</name>
    <description>RabbitMQ for Spring Boot</description>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.amqp</groupId>
            <artifactId>spring-rabbit-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Note : The message which we are publishing should be a String or byte[] or Serializable.

After running the spring boot application send a get request

URL: http://localhost:8080/rmq/publish/message/xml

You can see that the messages are published in the Queues

How to consume a message ?

As We have messages in our queue so lets consume them

First we need a consumer class Then a config class to allow the java classes to be received.

Now after running the project i received all the messages in the queue.

Headers Exchange in Spring Boot:

Publishing and consuming messages using Headers Exchange is little different. you can use this similar method in other exchanges as well.

Publisher Method:

    @Autowired
    private ObjectMapper objectMapper;

    @GetMapping("/header/{type}")
    public String testAPI(@PathVariable("type") String type) throws IOException {
        File f = new File(1, type);

        // Serialize File object to JSON
        String jsonFile = objectMapper.writeValueAsString(f);

        Message message = MessageBuilder.withBody(jsonFile.getBytes())
                .setContentType(MessageProperties.CONTENT_TYPE_JSON)
                .setHeader("key", "header")
                // .setHeader("key2", "value2")
                .build();

        rabbitTemplate.send("headers-exchange", "", message);
        return "Success";
    }

Consumer Method:

    @Autowired
    private ObjectMapper objectMapper;

    @RabbitListener(queues = "header-queue")
    public void getMessageFromHeaderQueue(Message message) throws IOException, ClassNotFoundException {        
        try {
            System.out.println("RabbitConsumers.getMessageFromHeaderQueue()");
            String jsonContent = new String(message.getBody());
            File file = objectMapper.readValue(jsonContent, File.class);

            // Process the File object as needed
            System.out.println("Received File: " + file.getFileType());

            // Now you can work with the 'file' object as needed
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Now We have understood how to use RabbitMQ using spring boot. Please folow my series below to learn more about RabbitMQ.

https://codeinjava.hashnode.dev/series/rabbitmq

Did you find this article valuable?

Support Java Blogs By Hemant by becoming a sponsor. Any amount is appreciated!