In this tutorial, we are going to see how to implement a Spring Boot RabbitMQ Consumer Messages example.

Spring Boot RabbitMQ Consumer Messages:

In the previous tutorial, we saw how to publish messages to RabbitMQ queue, if you haven’t check that I recommend you to go through once, so that it may be helpful to understand the full flow of this example.

Prerequisites:

  • Install RabbitMQ on your machine; if you are working on Windows, you can check my previous tutorials to install RabbitMQ on windows 10.
  • Start RabbitMQ server

Technologies:

  • Spring Boot Starter AMQP
  • Spring Boot Starter JSON
  • Lombok
  • Java8

Project Structure:

Spring Boot RabbitMQ Consumer Messages Example

Project Dependencies:

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 http://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>2.1.4.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
  </parent>
  <groupId>com.onlinetutorialspoint</groupId>
  <artifactId>Spring-Boot-RabbitMQ-Consumer-Example</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>Spring-Boot-RabbitMQ-Consumer-Example</name>
  <description>Spring Boot RabbitMQ Consumer Example</description>
  <properties>
    <java.version>1.8</java.version>
  </properties>
  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-amqp</artifactId>
    </dependency>
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <optional>true</optional>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-json</artifactId>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>
</project>

Creating Item model bean – It represents the JSON message structure.

Item.java
package com.onlinetutorialspoint.model;

import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

@JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class,property = "@id",scope = Item.class)
@Data
@ToString
@NoArgsConstructor
public class Item {
    private String itemName;
    private String category;
    private String description;
}

Let the Spring Boot know about your RabbitMQ server details through application.properties.

application.properties
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest

Creating RabbitMQConfig – It has JsonMessageConverter which will be responsible for converting an object to JSON.

RabbitMQConfig.java
package com.onlinetutorialspoint.config;

import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitMQConfig {
    @Bean
    public MessageConverter jsonMessageConverter() {
        return new Jackson2JsonMessageConverter();
    }
}

We are creating RabbitMQConsumerService – Responsible to listen on the configured RabbitMQ queue.

RabbitMQConsumerService.java
package com.onlinetutorialspoint.service;

import com.onlinetutorialspoint.model.Item;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

@Service
public class RabbitMQConsumerService {
    private static final String QUEUE="items-queue";

    @RabbitListener(queues = QUEUE)
    public void receiveMessage(Item item) {
        System.out.println("Received Message from Items Queue >>"+item);
    }
}

Main class

SpringBootRabbitMqConsumerApplication.java
package com.onlinetutorialspoint;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootRabbitMqConsumerApplication {

  public static void main(String[] args) {
    SpringApplication.run(SpringBootRabbitMqConsumerApplication.class, args);
  }

}

Run the application:

Terminal
mvn clean install
mvn spring-boot:run
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.4.RELEASE)

2019-06-15 14:24:15.102  INFO 2052 --- [           main] .o.SpringBootRabbitMqConsumerApplication : Starting SpringBootRabbitMqConsumerApplication on DESKTOP-RN4SMHT with PID 2052 (D:\wo
rk\Spring-Boot-RabbitMQ-Consumer-Example\target\classes started by Lenovo in D:\work\Spring-Boot-RabbitMQ-Consumer-Example)
2019-06-15 14:24:15.139  INFO 2052 --- [           main] .o.SpringBootRabbitMqConsumerApplication : No active profile set, falling back to default profiles: default
2019-06-15 14:24:17.926  INFO 2052 --- [           main] o.s.a.r.c.CachingConnectionFactory       : Attempting to connect to: [localhost:5672]
2019-06-15 14:24:18.068  INFO 2052 --- [           main] o.s.a.r.c.CachingConnectionFactory       : Created new connection: rabbitConnectionFactory#13676ff5:0/SimpleConnection@75ddfb80 [
delegate=amqp://guest@127.0.0.1:5672/, localPort= 64511]
2019-06-15 14:24:18.194  INFO 2052 --- [           main] .o.SpringBootRabbitMqConsumerApplication : Started SpringBootRabbitMqConsumerApplication in 4.493 seconds (JVM running for 12.501
)

Let’s Validate the things:

To validate the app, we should have to do multiple things.

Step1: Start RabbitMQ server

Terminal
C:\Program Files\RabbitMQ Server\rabbitmq_server-3.7.15\sbin>rabbitmq-server.bat start
"WARNING: Using RABBITMQ_ADVANCED_CONFIG_FILE: C:\Users\Lenovo\AppData\Roaming\RabbitMQ\advanced.config"

  ##  ##
  ##  ##      RabbitMQ 3.7.15. Copyright (C) 2007-2019 Pivotal Software, Inc.
  ##########  Licensed under the MPL.  See https://www.rabbitmq.com/
  ######  ##
  ##########  Logs: C:/Users/Lenovo/AppData/Roaming/RabbitMQ/log/RABBIT~1.LOG
                    C:/Users/Lenovo/AppData/Roaming/RabbitMQ/log/rabbit@DESKTOP-RN4SMHT_upgrade.log

              Starting broker...
 completed with 3 plugins.

Step2: Publish some messages to RabbitMQ queue. I am using our previous publisher example to publish messages.

Note: The publisher application is running on 8090 port and receiver application running on 8080 port.
Spring Boot RabbitMQ Consumer Messages Example 3-min

Step3: Check the consumer application logs, where you could see the consumed message like following.

Application Logs
Received Message from Items Queue >>Item(itemName=Spring in Action, category=Books, description=Spring in Action)

Done!

References:

Download Source From GIT:

Happy Learning 🙂