RabbitMQ – How to create Spring RabbitMQ Producer/Consumer applications with SpringBoot

RabbitMQ is one of the most popular open source message broker which meets high-scale, high-availability requirements. So in the tutorial, JavaSampleApproach will guide how to create Spring RabbitMQ Producer/Consumer applications by SpringBoot.

Related articles:
How to use Spring JMS with ActiveMQ – JMS Consumer and JMS Producer | Spring Boot
How to start Spring Kafka Application with Spring Boot
RabbitMq – How to create Spring RabbitMq Publish/Subcribe pattern with SpringBoot
RabbitMQ – How to send/receive Java object messages with Spring RabbitMq | SpringBoot

I. SpringBoot RabbitMQ

In the tutorial, we create 2 SpringBoot applications {Producer, Consumer} for working with RabbitMQ:

rabbitmq - architecture - copyright

Producer will send messages to RabbitMQ Exchanges with a routingKey. RabbitMQ uses routingKey to determine which queues for routing messages.
Consumer listens on a RabbitMQ Queue to receive messages.

With SpringBoot, we use spring.rabbitmq.* for controlling RabbitMQ configuration:

Producer uses AmqpTemplate to send messages:

Consumer uses @RabbitListener to recieve messages:

II. Practice

We create 2 SpringBoot projects {Producer, Consumer}:

Spring rabbitmq producer/consumer application - structure of projects

Step to do:
– Create SpringBoot projects
– Create Producer/Consumer
– Setup RabbitMQ exchange, queue
– Run and check results

1. Create SpringBoot projects

Create 2 SpringBoot projects {Producer, Consumer}, then add dependency:

With SpringRabbitMqProducer we add more web for creating RestController:

2. Create Producer/Consumer
2.1 Create Producer

– Add RabbitMq configuration:

– Create RabbitMq Producer:

– Implement a sending restApi:

2.2 Create Consumer

– Add RabbitMq configuration

– Create RabbitMq Consumer:

3. Setup RabbitMQ Exchange, Queue

Enable rabbitmq_management by cmd: rabbitmq-plugins enable rabbitmq_management --online
Go to: http://localhost:15672. Then login with user/password: guest/guest

rabbit monitoring overview

3.1 Add exchange

Go to http://localhost:15672/#/exchanges.
– Add exchange: jsa.direct

rabbitmq - add exchange

3.2 Add queue

Go to http://localhost:15672/#/queues.
– Add a queue: jsa.queue

rabbitmq - create a queue

Binding the queue with above exchange:

binding queue with exchange

4. Run and check results

Build and run 2 SpringBoot projects with commandlines {mvn clean install, mvn spring-boot:run}.
With the SpringBoot Producer, send a message: http://localhost:8080/send?msg=Hello World!

At the SpringBoot Subcriber, we will get a console message: Recieved Message: Hello World!

Check connections -> go to http://localhost:15672/#/connections:

rabbit connections

III. Sourcecode

SpringRabbitMqProducer
SpringRabbitMqConsumer


Related Posts



Got Something To Say:

Your email address will not be published. Required fields are marked *

*