An open API service indexing awesome lists of open source software.

https://github.com/showpune/gs-messaging-servicebus


https://github.com/showpune/gs-messaging-servicebus

Last synced: about 1 year ago
JSON representation

Awesome Lists containing this project

README

          

:toc:
:icons: font
:source-highlighter: prettify
:project_id: gs-messaging-rabbitmq
:build_name: messaging-rabbitmq
:build_version: 0.0.1-SNAPSHOT
:java_version: 17
:build_system: gradle
:network_container: guide-rabbit
:omit_native_build: y

This guide walks you through the process of creating a Spring Boot application that publishes and subscribes to a RabbitMQ AMQP server.

== What You Will Build

You will build an application that publishes a message by using Spring AMQP's `RabbitTemplate` and subscribes to the message on a POJO by using `MessageListenerAdapter`.

include::https://raw.githubusercontent.com/spring-guides/getting-started-macros/main/guide_introduction.adoc[]

== Setting up the RabbitMQ Broker

Before you can build your messaging application, you need to set up a server to handle receiving and sending messages.
include::https://raw.githubusercontent.com/spring-guides/getting-started-macros/main/docker_compose_support.adoc[]

If you choose to run the RabbitMQ server yourself instead of using Spring Boot Docker Compose support, you have a few options:

* https://www.rabbitmq.com/download.html[Download the server^] and manually run it
* Install with Homebrew, if you use a Mac
* Manually run the `compose.yaml` file with `docker-compose up`

If you go with any of these alternate approaches, you should remove the `spring-boot-docker-compose` dependency from the Maven or Gradle build file.
You will also need to add configuration to an `application.properties` file, as described in greater detail in the <<_preparing_to_build_the_application>> section.
As mentioned earlier, this guide assumes that you use Docker Compose support in Spring Boot, so additional changes to `application.properties` are not required at this point.

[[initial]]
== Starting with Spring Initializr

You can use this https://start.spring.io/#!type=maven-project&language=java&packaging=jar&groupId=com.example&artifactId=messaging-rabbitmq&name=messaging-rabbitmq&description=Demo%20project%20for%20Spring%20Boot&packageName=com.example.messaging-rabbitmq&dependencies=amqp,docker-compose[pre-initialized project^] and click Generate to download a ZIP file. This project is configured to fit the examples in this guide.

To manually initialize the project:

. Navigate to https://start.spring.io[start.spring.io^].
This service pulls in all the dependencies you need for an application and does most of the setup for you.
. Choose either Gradle or Maven and the language you want to use. This guide assumes that you chose Java.
. Click *Dependencies* and select *Spring for RabbitMQ* and *Docker Compose Support*.
. Click *Generate*.
. Download the resulting ZIP file, which is an archive of an application that is configured with your choices.

NOTE: If your IDE has the Spring Initializr integration, you can complete this process from your IDE.

== Create a RabbitMQ Message Receiver

With any messaging-based application, you need to create a receiver that responds to
published messages. The following listing (from
`src/main/java/com/example/messagingrabbitmq/Receiver.java`) shows how to do so:

====
[source,java,tabsize=2]
----
include::complete/src/main/java/com/example/messagingrabbitmq/Receiver.java[]
----
====

The `Receiver` is a POJO that defines a method for receiving messages. When you register
it to receive messages, you can name it anything you want.

NOTE: For convenience, this POJO also has a `CountDownLatch`. This lets it signal that the
message has been received. This is something you are not likely to implement in a
production application.

== Register the Listener and Send a Message

Spring AMQP's `RabbitTemplate` provides everything you need to send and receive messages
with RabbitMQ. However, you need to:

- Configure a message listener container.
- Declare the queue, the exchange, and the binding between them.
- Configure a component to send some messages to test the listener.

NOTE: Spring Boot automatically creates a connection factory and a RabbitTemplate,
reducing the amount of code you have to write.

You will use `RabbitTemplate` to send messages, and you will register a `Receiver` with
the message listener container to receive messages. The connection factory drives both,
letting them connect to the RabbitMQ server. The following listing (from
`src/main/java/com/example/messagingrabbitmq/MessagingRabbitmqApplication.java`) shows how
to create the application class:

====
[source,java,tabsize=2]
----
include::complete/src/main/java/com/example/messagingrabbitmq/MessagingRabbitmqApplication.java[]
----
====

The `@SpringBootApplication` annotation offers a number of benefits, as described in the https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#getting-started.first-application.code.spring-boot-application[reference documentation].

The bean defined in the `listenerAdapter()` method is registered as a message listener in
the container (defined in `container()`). It listens for messages on the `spring-boot`
queue. Because the `Receiver` class is a POJO, it needs to be wrapped in the
`MessageListenerAdapter`, where you specify that it invokes `receiveMessage`.

NOTE: JMS queues and AMQP queues have different semantics. For example, JMS sends queued
messages to only one consumer. While AMQP queues do the same thing, AMQP producers do not
send messages directly to queues. Instead, a message is sent to an exchange, which can go
to a single queue or fan out to multiple queues, emulating the concept of JMS topics.

The message listener container and receiver beans are all you need to listen for messages.
To send a message, you also need a Rabbit template.

The `queue()` method creates an AMQP queue. The `exchange()` method creates a topic
exchange. The `binding()` method binds these two together, defining the behavior that
occurs when `RabbitTemplate` publishes to an exchange.

NOTE: Spring AMQP requires that the `Queue`, the `TopicExchange`, and the `Binding` be
declared as top-level Spring beans in order to be set up properly.

In this case, we use a topic exchange, and the queue is bound with a routing key of
`foo.bar.#`, which means that any messages sent with a routing key that begins with
`foo.bar.` are routed to the queue.

== Send a Test Message

In this sample, test messages are sent by a `CommandLineRunner`, which also waits for the
latch in the receiver and closes the application context. The following listing (from
`src/main/java/com.example.messagingrabbitmq/Runner.java`) shows how it works:

====
[source,java,tabsize=2]
----
include::complete/src/main/java/com/example/messagingrabbitmq/Runner.java[]
----
====

Notice that the template routes the message to the exchange with a routing key of
`foo.bar.baz`, which matches the binding.

In tests, you can mock out the runner so that the receiver can be tested in isolation.

== Run the Application

The `main()` method starts that process by creating a Spring application context. This
starts the message listener container, which starts listening for messages. There is a
`Runner` bean, which is then automatically run. It retrieves the `RabbitTemplate` from the
application context and sends a `Hello from RabbitMQ!` message on the `spring-boot` queue.
Finally, it closes the Spring application context, and the application ends.

You can run the main method through your IDE.
Note that, if you have cloned the project from the solution repository, your IDE may look in the wrong place for the `compose.yaml` file.
You can configure your IDE to look in the correct place or you could use the command line to run the application.
The `./gradlew bootRun` and `./mvnw spring-boot:run` commands will launch the application and automatically find the compose.yaml file.

== Preparing to Build the Application

To run the code without Spring Boot Docker Compose support, you need a version of RabbitMQ running locally to connect to.
To do this, you can use Docker Compose, but you must first make two changes to the `compose.yaml` file.
First, modify the `ports` entry in `compose.yaml` to be `'5672:5672'`.
Second, add a `container_name`.

The `compose.yaml` should now be:
----
services:
rabbitmq:
container_name: 'guide-rabbit'
image: 'rabbitmq:latest'
environment:
- 'RABBITMQ_DEFAULT_PASS=secret'
- 'RABBITMQ_DEFAULT_USER=myuser'
ports:
- '5672:5672'
----

You can now run `docker-compose up` to start the RabbitMQ service.
Now you should have an external RabbitMQ server that is ready to accept requests.

Additionally, you need to tell Spring how to connect to the RabbitMQ server (this was handled automatically with Spring Boot Docker Compose support).
Add the following code to a new `application.properties` file in `src/main/resources`:
----
spring.rabbitmq.password=secret
spring.rabbitmq.username=myuser
----

include::https://raw.githubusercontent.com/spring-guides/getting-started-macros/main/build_and_execute_guide.adoc[]

Regardless of how you chose to build and run the application, you should see the following output:

====
[source,bash]
----
Sending message...
Received
----
====

== Summary

Congratulations! You have just developed a simple publish-and-subscribe application with
Spring and RabbitMQ. You can do more with
https://docs.spring.io/spring-amqp/reference/#_introduction[Spring and RabbitMQ^]
than what is covered here, but this guide should provide a good start.

== See Also

Additional https://github.com/spring-projects/spring-amqp-samples[Spring AMQP Samples]

The following guides may also be helpful:

* https://spring.io/guides/gs/messaging-redis/[Messaging with Redis]
* https://spring.io/guides/gs/messaging-jms/[Messaging with JMS]
* https://spring.io/guides/gs/spring-boot/[Building an Application with Spring Boot]

include::https://raw.githubusercontent.com/spring-guides/getting-started-macros/main/footer.adoc[]