RabbitMQ Queue Listener Java Spring Boot Code Example


Step 1: Add RabbitMQ Spring Boot Dependecny

Make sure to add the rabbitMQ Spring boot dependency in your maven/gradle configuration file.

spring-boot-starter-amqp

Step 2: Create Topic Exchange and Queue

@Configuration
public class RabbitMQConfig {

    private static final String EXCHANGE_NAME = "rmq_c2c_exchange";
    private static final String QUEUE_NAME = "rmq_c2c_queue";

    @Bean
    public TopicExchange exchange() {
        System.out.println("Topic Exchange created!");
        return new TopicExchange(EXCHANGE_NAME);
    }

    @Bean
    public Queue queue() {
        return new Queue(QUEUE_NAME, true);
    }

    @Bean
    public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory) {
        return new RabbitAdmin(connectionFactory);
    }

}

Step 3: Create the Queue Listener @RabbitListener

Annotate your method with @RabbitListener to make it a queue listener.

@Component
public class RmqQueueListener {

    @RabbitListener(queues = "rmq_c2c_queue")
    public void processMessage(String message) {
        System.out.println("Message: " + message);
    }
}

Step 4: Add RabbitMQ Properties in application.properties

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


Step 5: Create a RabbitMQ docker instance

run -d --hostname uat-rabbitmq1 --name uat-rabbitmq1 -p 15672:15672 -p 5672:5672 rabbitmq:management

Step 5: Publush a message

Run the Spring Boot Application and login to the RabbitMQ Management client on your browser at http://localhost:15672 and go to Queue tab and publish a message.

Publish message to Queue RabbitMQ

On your IDE console you should see the message received by the RabbitMQ Listener method.

Message: This is a test message

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap