Expand Authors Top

If you have a few years of experience in the Java ecosystem and you’d like to share that with the community, have a look at our Contribution Guidelines.

Expanded Audience – Frontegg – Security (partner)
announcement - icon User management is very complex, when implemented properly. No surprise here.

Not having to roll all of that out manually, but instead integrating a mature, fully-fledged solution - yeah, that makes a lot of sense.
That's basically what Frontegg is - User Management for your application. It's focused on making your app scalable, secure and enjoyable for your users.
From signup to authentication, it supports simple scenarios all the way to complex and custom application logic.

Have a look:

>> Elegant User Management, Tailor-made for B2B SaaS

November Discount Launch 2022 – Top
We’re finally running a Black Friday launch. All Courses are 30% off until the end of this week:

>> GET ACCESS NOW

NPI – Lightrun – Spring (partner)

We rely on other people’s code in our own work. Every day. It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production - debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky. It’s difficult to understand what talks to what and, specifically, which part of the underlying library is at fault.

Lightrun is a new kind of debugger.

It's one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics. No hotfixes, redeployments, or restarts required.

Learn more in this quick, 5-minute Lightrun tutorial:

>> The Essential List of Spring Boot Annotations and Their Use Cases

1. Overview

In this tutorial, we'll explore message-based communication over AMQP using the Spring AMQP framework. First, we'll cover some of the key concepts of messaging. Then, we'll move on to a practical example.

2. Message-Based Communication

Messaging is a technique for communicating between applications. It relies on asynchronous message-passing instead of synchronous request response-based architecture. Producers and consumers of messages are decoupled by an intermediate messaging layer known as a message broker. A message broker provides features like persistent storage of messages, message filtering, and message transformation.

In a case of messaging between applications written in Java, the JMS (Java Message Service) API is commonly used. For interoperability between different vendors and platforms, we won't be able to use JMS clients and brokers. This is where AMQP comes in handy.

3. AMQP – Advanced Message Queuing Protocol

AMQP is an open standard wire specification for asynchronous message communication. It provides a description of how a message should be constructed.

3.1. How Amqp Is Different from Jms

Since AMQP is a platform-neutral binary protocol standard, libraries can be written in different programming languages, and run on different environments.

There is no vendor based protocol lock-in, as is the case when migrating from one JMS broker to another. For more details refer to JMS vs AMQP and Understanding AMQP. Some of the widely used AMQP brokers are RabbitMQ, OpenAMQ, and StormMQ.

3.2. AMQP Entities

Briefly, AMQP is made up of Exchanges, Queues, and Bindings:

  • Exchanges are like post offices or mailboxes and clients publish a message to an AMQP exchange. There are four built-in exchange types
    • Direct Exchange – Routes messages to a queue by matching a complete routing key
    • Fanout Exchange – Routes messages to all the queues bound to it
    • Topic Exchange – Routes messages to multiple queues by matching a routing key to a pattern
    • Headers Exchange – Routes messages based on message headers
  • Queues are bound to an exchange using a routing key
  • Messages are sent to an exchange with a routing key. The exchange then distributes copies of messages to queues

For more details, have a look at AMQP Concepts and Routing Topologies.

3.3. Spring AMQP

Spring AMQP comprises two modules: spring-amqp and spring-rabbit. Together, these modules provide abstractions for:

  • AMQP entities – we create entities with the Message, Queue, Binding, and Exchange classes
  • Connection Management – we connect to our RabbitMQ broker by using a CachingConnectionFactory
  • Message Publishing – we use a RabbitTemplate to send messages
  • Message Consumption – we use a @RabbitListener to read messages from a queue

4. Setup a Rabbitmq Broker

We need a RabbitMQ broker available for us to connect to. The simplest way to do this is by using Docker to fetch and run a RabbitMQ image for us:

docker run -d -p 5672:5672 -p 15672:15672 --name my-rabbit rabbitmq:3-management

We expose port 5672 so that our application can connect to RabbitMQ.

And, we expose port 15672 so that we can see what our RabbitMQ broker is doing via either the management UI: http://localhost:15672 or the HTTP API: http://localhost:15672/api/index.html.

5. Creating Our Spring Amqp Application

So, now let's create our application to send and receive a simple “Hello, world!” message by using Spring AMQP.

5.1. Maven Dependencies

In order to add the spring-amqp and spring-rabbit modules to our project, we add the spring-boot-starter-amqp dependency to our pom.xml:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-amqp</artifactId>
        <version>2.2.2.RELEASE</version>
    </dependency>
</dependencies>

We can find the latest version in at Maven Central.

5.2. Connecting to Our Rabbitmq Broker

We'll use Spring Boot's auto-configuration to create our ConnectionFactory, RabbitTemplate, and RabbitAdmin beans. As a result, we get a connection to our RabbitMQ broker on port 5672 using the default username and password of “guest”. So, we just annotate our application with @SpringBootApplication:

@SpringBootApplication
public class HelloWorldMessageApp {
   // ...
}

5.3. Create Our Queue

In order to Create Our Queue, we simply define a bean of type Queue. RabbitAdmin will find this and bind it to the default exchange with a routing key of “myQueue”:

@Bean
public Queue myQueue() {
    return new Queue("myQueue", false);
}

We set the queue to be non-durable so that the queue and any messages on it will be removed when RabbitMQ is stopped. Note, however, that restarting our application will have no effect on the queue.

5.4. Send Our Message

Let's use the RabbitTemplate to send our “Hello, world!” message:

rabbitTemplate.convertAndSend("myQueue", "Hello, world!");

5.5. Consume Our Message

We'll implement a message consumer by annotating a method with @RabbitListener:

@RabbitListener(queues = "myQueue")
public void listen(String in) {
    System.out.println("Message read from myQueue : " + in);
}

6. Running Our Application

First, we start the RabbitMQ broker:

docker run -d -p 5672:5672 -p 15672:15672 --name my-rabbit rabbitmq:3-management

Then, we run the spring boot application by running HelloWorldMessage.java, executing the main() method:

mvn spring-boot:run -Dstart-class=com.baeldung.springamqp.simple.HelloWorldMessageApp

While the application is running we will see that:

  • The application sends a message to the default exchange with “myQueue” as the routing key
  • Then, the queue “myQueue” receives the message
  • Finally, the listen method consumes the message from “myQueue” and prints it on the console

We can also use the RabbitMQ management page at http://localhost:15672 to see that our message has been sent and consumed.

7. Conclusion

In this tutorial, we covered messaging-based architecture over AMQP protocol using Spring AMQP for communication between applications.

The complete source code and all code snippets for this tutorial are available on the GitHub project.

November Discount Launch 2022 – Bottom
We’re finally running a Black Friday launch. All Courses are 30% off until the end of this week:

>> GET ACCESS NOW

Generic footer banner
Comments are closed on this article!