Learn Spring Β· 13/15

Event-Driven Architecture Basics

9 min read

Event-Driven Architecture Basics 🏰

Welcome, fearless developer, to the world of Event-Driven Architecture (EDA) in Spring! Ever felt like your application components are a little too close for comfort, like they're constantly in each other's business? If one part stumbles, does it bring the whole house of cards down? If so, you've come to the right place. We're about to learn how to build more resilient, scalable, and maintainable systems by letting our components communicate without being tightly attached at the hip.

What's the Big Deal with Event-Driven Architecture?

In many traditional applications, components directly call each other. Component A needs something from Component B, so it calls a method on Component B and waits for a response. This is called synchronous, request-response communication. It's simple and works well for many scenarios.

The Problem: Imagine a popular online store. When a customer places an order, several things need to happen: the inventory needs to be updated, a shipping label needs to be created, an invoice needs to be generated, and a confirmation email needs to be sent.

If the OrderService is responsible for calling the InventoryService, ShippingService, BillingService, and NotificationService directly, we run into a few problems:

  • Tight Coupling: The OrderService is now tightly coupled to all these other services. If the NotificationService is down, the entire order process might fail.
  • Scalability Issues: What if we need to add a new service, like a FraudDetectionService, every time an order is placed? We'd have to modify the OrderService code. This becomes a bottleneck.
  • Poor User Experience: The customer has to wait for all these operations to complete before getting a confirmation that their order was successful.

The Solution: Event-Driven Architecture! Instead of the OrderService directly commanding other services, it simply shouts into the void, "An order has been placed!" and goes on with its life. This shout is an event. Other services that care about new orders are listening for this event and will react accordingly, all without the OrderService even knowing they exist. This is asynchronous communication.


1. Decoupling Components Internally with Spring Application Events 🧩

Let's start our journey inside our Spring application. Before we venture out into the wild world of external systems, we can achieve a great deal of decoupling right here at home using Spring's built-in event mechanism.

Think of it like an internal company memo. Instead of one department head running around to every other department to tell them what to do, they post a memo on a central bulletin board. Anyone who needs to know about that memo can read it and act on it.

The Core Components: ApplicationEvent and ApplicationListener

Spring's eventing mechanism is elegantly simple and revolves around two main players:

  • ApplicationEvent: This is the memo itself. It's a class that represents something that has happened in the application.
  • ApplicationListener: This is the employee who is interested in certain memos. They subscribe to specific types of events and get notified when they occur.

Let's see this in action. Imagine we have a user registration process. After a new user is created, we want to send them a welcome email.

The Old Way (Tightly Coupled):

java
@Service
public class UserService {

    private final EmailService emailService;

    // Constructor injection

    public void registerUser(String username, String email) {
        // ... logic to save the user to the database ...
        System.out.println("User " + username + " registered.");

        // Directly calling the EmailService
        emailService.sendWelcomeEmail(email);
    }
}

Here, UserService has a direct dependency on EmailService. If sending the email fails, what happens to the user registration?

The Spring Events Way (Decoupled):

First, we define our event. It's good practice to create a custom event class that extends ApplicationEvent.

UserRegisteredEvent.java

java
import org.springframework.context.ApplicationEvent;

public class UserRegisteredEvent extends ApplicationEvent {

    private final String email;

    public UserRegisteredEvent(Object source, String email) {
        super(source);
        this.email = email;
    }

    public String getEmail() {
        return email;
    }
}

Our event carries the necessary information, in this case, the user's email.

Now, our UserService will publish this event using an ApplicationEventPublisher.

UserService.java

java
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;

@Service
public class UserService {

    private final ApplicationEventPublisher eventPublisher;

    // Spring injects the ApplicationEventPublisher for us
    public UserService(ApplicationEventPublisher eventPublisher) {
        this.eventPublisher = eventPublisher;
    }

    public void registerUser(String username, String email) {
        // ... logic to save the user to the database ...
        System.out.println("User " + username + " registered.");

        // Publish the event
        UserRegisteredEvent event = new UserRegisteredEvent(this, email);
        eventPublisher.publishEvent(event);
    }
}

Notice how the UserService no longer knows or cares about the EmailService. Its only job is to announce that a user has been registered.

Finally, we create a listener that will react to our event.

EmailService.java

java
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Service;

@Service
public class EmailService implements ApplicationListener<UserRegisteredEvent> {

    @Override
    public void onApplicationEvent(UserRegisteredEvent event) {
        sendWelcomeEmail(event.getEmail());
    }

    public void sendWelcomeEmail(String email) {
        // ... logic to send the email ...
        System.out.println("Sending a welcome email to " + email);
    }
}

By implementing ApplicationListener<UserRegisteredEvent>, our EmailService tells Spring, "Hey, whenever a UserRegisteredEvent happens, let me know!"

We've successfully decoupled the UserService from the EmailService! Now, if we want to, say, assign a default user role upon registration, we can simply create a new UserRoleService that also listens for the UserRegisteredEvent, without ever touching the UserService. Beautiful, isn't it? ✨


2. Publishing and Listening to Custom Domain Events (@EventListener) 🎧

While implementing ApplicationListener is the classic way to do things, Spring, being the helpful framework it is, provides an even simpler, annotation-based approach: @EventListener.

This is like setting up a notification on your phone for a specific app. You don't need a complex setup; you just tell your phone, "When this app sends a notification, buzz me."

Let's refactor our EmailService to use this modern approach.

EmailService.java (with @EventListener)

java
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;

@Service
public class EmailService {

    @EventListener
    public void handleUserRegisteredEvent(UserRegisteredEvent event) {
        sendWelcomeEmail(event.getEmail());
    }

    public void sendWelcomeEmail(String email) {
        // ... logic to send the email ...
        System.out.println("Sending a welcome email to " + email);
    }
}

That's it! We just annotate a method with @EventListener, and Spring is smart enough to figure out which event to listen for based on the method's parameter type (UserRegisteredEvent). This is the preferred way in modern Spring applications due to its conciseness.

Under the Hood πŸ•΅οΈβ€β™‚οΈ

When your Spring application starts, it scans for beans with @EventListener annotations. It then creates an ApplicationListener for each of these methods behind the scenes and registers them. So, while it looks like magic, it's just Spring doing the heavy lifting for you.

A Funny Exaggeration 🀑

Imagine you're a medieval king (your UserService). After winning a battle (registering a user), you don't want to run to the cook to prepare a feast, to the bard to write a song, and to the stablehand to feed your horse. That's exhausting! Instead, you have your town crier (ApplicationEventPublisher) announce the victory. The cook, bard, and stablehand (@EventListeners) hear the announcement and do their respective jobs. The king doesn't even need to know their names! He just needs his feast, his song, and a happy horse.


3. Stepping Outside: Introduction to External Message Brokers (RabbitMQ Basics) πŸ‡

Internal events are fantastic for decoupling components within a single application. But what happens when you have multiple, separate applications (microservices) that need to communicate? The OrderService might be one application, and the NotificationService a completely different one.

This is where Message Brokers come into play. A message broker is a piece of software that acts as a post office for your applications. Producers send messages to the broker, and consumers receive messages from it.

Why use a message broker?

  • Decoupling Services: Services don't need to know each other's network locations. They only need to know how to talk to the broker.
  • Asynchronous Communication: A service can send a message and not wait for a response, improving performance and responsiveness.
  • Load Balancing: Multiple instances of a service can consume messages from the same queue, distributing the workload.
  • Resilience: If the consuming service is down, the message broker will hold onto the messages until the consumer is back online.

Enter RabbitMQ 🐰

RabbitMQ is one of the most popular open-source message brokers. It's like a highly organized and reliable postal service.

Core RabbitMQ Concepts (The Bare Essentials):

  • Producer: The application that sends a message.
  • Consumer: The application that receives a message.
  • Queue: A mailbox where messages are stored until they are picked up by a consumer.
  • Exchange: The post office's sorting room. A producer sends a message to an exchange, and the exchange decides which queue(s) it should go to based on rules called bindings.
  • Binding: A link between an exchange and a queue.

Getting Started with Spring AMQP and RabbitMQ

Spring makes it incredibly easy to work with RabbitMQ through the Spring AMQP project.

Step 1: Add the Dependency

In your pom.xml (for Maven), add the Spring Boot starter for RabbitMQ:

xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

Step 2: Configure the Connection

In your application.properties or application.yml, tell Spring where to find your RabbitMQ server.

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

(These are the default credentials for a local RabbitMQ installation).

Step 3: Sending a Message (Producer)

We'll use the RabbitTemplate, a helper class provided by Spring AMQP.

OrderService.java

java
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

@Service
public class OrderService {

    private final RabbitTemplate rabbitTemplate;
    private static final String EXCHANGE_NAME = "order-exchange";
    private static final String ROUTING_KEY = "order.created";


    public OrderService(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
    }

    public void createOrder(Order order) {
        // ... save order to database ...
        System.out.println("Order created: " + order.getId());

        // Send a message to RabbitMQ
        rabbitTemplate.convertAndSend(EXCHANGE_NAME, ROUTING_KEY, order);
    }
}

Step 4: Receiving a Message (Consumer)

In our NotificationService, we can use the @RabbitListener annotation to declare a method as a consumer for a specific queue.

NotificationService.java

java
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

@Service
public class NotificationService {

    @RabbitListener(queues = "notification-queue")
    public void handleOrderCreated(Order order) {
        System.out.println("Received order for notification: " + order.getId());
        // ... logic to send an email/SMS notification ...
    }
}

Hold on, where did notification-queue and order-exchange come from? πŸ€”

Good question! We need to declare them. Spring Boot can do this for us automatically if we define them as beans in a configuration class.

RabbitMQConfig.java

java
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitMQConfig {

    @Bean
    Queue queue() {
        return new Queue("notification-queue", false);
    }

    @Bean
    TopicExchange exchange() {
        return new TopicExchange("order-exchange");
    }

    @Bean
    Binding binding(Queue queue, TopicExchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with("order.created");
    }
}

Now, when the OrderService sends a message with the routing key order.created to the order-exchange, the exchange sees the binding and forwards the message to the notification-queue, where our @RabbitListener is waiting to pick it up.

You've just taken your first step into a larger, more distributed world! By using a message broker, your services can now live on different servers, be written in different languages, and scale independently, all while communicating seamlessly.


Further Reading & References πŸ“š

Challenge

You are working on an e-commerce application where the OrderService is tightly coupled with other services. Your task is to refactor the code to use Spring's internal event-driven mechanism for decoupling.

When an order is successfully placed in the OrderService, an OrderPlacedEvent should be published. The InventoryService and NotificationService should then listen for this event and perform their respective actions without being directly called by the OrderService.

Your Tasks:

  1. Create the Event:

    • Complete the OrderPlacedEvent class. It must extend ApplicationEvent.
    • It needs a constructor that accepts the source object and the orderId (a String).
    • Add a public getter method for the orderId.
  2. Publish the Event:

    • In the OrderService, ensure the ApplicationEventPublisher is correctly injected.
    • Inside the placeOrder method, after the order is created, publish a new OrderPlacedEvent.
  3. Listen for the Event:

    • In the InventoryService, create a public method that listens for the OrderPlacedEvent. Annotate it with @EventListener. This method should take the OrderPlacedEvent as its only argument.
    • In the NotificationService, create a similar @EventListener method that also reacts to the OrderPlacedEvent.

Expected result

Your code should correctly implement Spring's internal event handling using the @EventListener annotation.

The OrderPlacedEvent class must extend ApplicationEvent and properly initialize the orderId via its constructor, along with providing a public getter.

The OrderService must use its injected ApplicationEventPublisher to call publishEvent() within the placeOrder method, passing a new instance of your event class.

Both InventoryService and NotificationService must contain a public method annotated with @EventListener. Each of these listener methods must accept OrderPlacedEvent as a parameter to process the event data.

Here is an example of a valid solution:

java
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;

public class OrderPlacedEvent extends ApplicationEvent {
    private final String orderId;

    public OrderPlacedEvent(Object source, String orderId) {
        super(source);
        this.orderId = orderId;
    }

    public String getOrderId() {
        return orderId;
    }
}

@Service
public class OrderService {
    private final ApplicationEventPublisher eventPublisher;

    public OrderService(ApplicationEventPublisher eventPublisher) {
        this.eventPublisher = eventPublisher;
    }

    public void placeOrder(String orderId) {
        System.out.println("Processing order: " + orderId);
        System.out.println("Order " + orderId + " has been placed successfully.");
        OrderPlacedEvent event = new OrderPlacedEvent(this, orderId);
        eventPublisher.publishEvent(event);
    }
}

@Service
public class InventoryService {
    @EventListener
    public void updateStock(OrderPlacedEvent event) {
        System.out.println("InventoryService: Stock updated for order: " + event.getOrderId());
    }
}

@Service
public class NotificationService {
    @EventListener
    public void sendConfirmation(OrderPlacedEvent event) {
        System.out.println("NotificationService: Confirmation email sent for order: " + event.getOrderId());
    }
}
java

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.