Steps to Implement Event Loop in Spring WebFlux

To Implement event loop in spring WebFlux, here we created a Spring Boot project which is maven type. For this project, we use below dependencies.

Project Dependencies:

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

Project Folder:

After creating the project, the structure will be like below:


Step 1: Main Class File

Once project is created, automatically Spring framework creates this class with main function and spring application execution starts from here only.

ProjectApplication.java:

Java
package com.app;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ProjectApplication {

    public static void main(String[] args) {
        SpringApplication.run(ProjectApplication.class, args);
    }

}


Step 2: Create Controller

We created a RestController class by using @RestController annotation with name EventHandler in main package of project. This class is used for define the API endpoints as well as defining the required business logic in this class. Below we provide that handler code.

EventHandler.java:

Java
package com.app;

import java.time.Duration;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@RestController
@RequestMapping("/api/")
public class EventHandler {

    @GetMapping("/welcome")
    public Mono<String> sayHello() {
        return Mono.just("Hello, Welcome to w3wiki!").delayElement(Duration.ofSeconds(3));
    }

    @GetMapping("/data")
    public Flux<String> getData() {
        return Flux.just("One", "Two", "Three", "Four").delayElements(Duration.ofSeconds(1));
    }
}
  • In the above class, we created two different types of APIs for checking event loop functionality in the Handler class.
  • First, we create a method named called sayHello(). This method returns String type of Mono object.
  • After this, we created one more method called getData() in the same way, this method is able to return the result in the form of flux of events.

Step 3: Run the Project

Once project development is completed, run the project as Spring Boot App or we can run this project by using Maven commends. Here, we run this project as Spring Boot App. This Project running on 8080 port number with Netty server by default.


Step 4: Test the API

Now test API endpoint. Here, we use Postman tool for API testing.

welcome API:

This API is GET Mapping.

http://localhost:8080/api/welcome

Output:


data API:

This API is GET Mapping.

http://localhost:8080/api/data

Output:


Event Loop in Action

  • Handling Requests: When a request hits the API endpoints, it is received by a Netty server which dispatches the request to one of the event loops in its EventLoopGroup.
  • Scheduling Delays: For the mono, the call to delayElement(Duration.ofSeconds(1)) does not block the event loop. Instead, it schedules a task to complete the Mono after 1 second. The event loop is free to handle other requests during this time.
  • Processing Flux: The Flux uses delayElements(Duration.ofSeconds(1)). Each element is emitted with a 1-second delay. The event loop schedules these emissions without blocking the thread.
  • Non-blocking Completion: Once the delay period is over, the event loop handles the completion of the Mono or the next element of the Flux. It invokes the registered callbacks, such as sending the response back to the client.


Event loop in Spring WebFlux

Spring WebFlux is a version of the Spring Framework that supports reactive programming, allowing for non-blocking, asynchronous code execution. At the core of its framework, the event loop model is designed to efficiently handle multiple simultaneous requests.

For example, if there are multiple event loops, each event loop group is assigned a socket channel, and each event loop is controlled by an event loop group. The event loop model of Spring WebFlux allows for the efficient handling of many concurrent requests with fewer threads, making it suitable for applications that require high scalability and responsiveness. This simple example shows the basics which has to create a non-blocking REST endpoint using Spring WebFlux.



  • In the diagram, it represents the event loop in Spring WebFlux
  • Here, all requests are received in a unique socket with an associated socket channel.
  • A request goes through the event loop via a channel pipeline, where a number of inbound channel handlers process the requests.
  • At end of the event loop, the response is returned to the client.

Key Features of Event Loop in Spring WebFlux:

  • Non-blocking I/O: Spring WebFlux uses non-blocking I/O to process requests. This means that there are no strings tied up waiting for I/O operations such as reading from the database or waiting for the network response to complete.
  • Reactor Core Integration: Spring WebFlux is built on top of Project Reactor, a responsive library for building non-blocking applications on the JVM.
  • Efficiency: The event loop model enables Spring WebFlux to handle a large number of concurrent transactions with a limited number of threads
  • Backpressure Support: Backpressure is a way to handle situations where data producers generate data faster than consumers can process it.
  • Asynchronous Event Handling: The event loop is responsible for asynchronous processing with events.
  • Scalability: The non-blocking nature and efficient use of resources in the event loop makes Spring WebFlux highly scalable
  • Minimum thread blocking: The event loop uses non-blocking I/O, with minimal thread blocking. This means threads are less likely to work waiting for tasks to complete and can instead be used to process more requests, improving overall performance

Similar Reads

Steps to Implement Event Loop in Spring WebFlux

To Implement event loop in spring WebFlux, here we created a Spring Boot project which is maven type. For this project, we use below dependencies....

Contact Us