WebFlux - Java Reactive Programming

March 08, 2025

Introduction

In modern web development, handling asynchronous, non-blocking operations efficiently is crucial for building high-performance applications. Spring WebFlux, introduced in Spring 5, is a fully reactive programming framework that enables developers to create scalable and efficient web applications using the Reactor library.

This blog explores the fundamentals of WebFlux, its benefits, key components, and how to build a simple REST API using WebFlux.

Why WebFlux?

Traditional Spring MVC follows a thread-per-request model, which can become a bottleneck when dealing with high concurrency and I/O-heavy operations. Spring WebFlux, on the other hand, is built on a reactive programming paradigm, which provides:

  • Non-blocking I/O: Efficient resource utilization, especially in high-load applications.
  • Event-driven architecture: Handles multiple requests concurrently without blocking threads.
  • Backpressure support: Prevents system overload by regulating data flow.
  • Functional and annotation-based programming models.

Key Components of WebFlux

Spring WebFlux uses Project Reactor for reactive programming. Key components include:

1. Mono & Flux

  • Mono<T>: Represents a single value or an empty response.
  • Flux<T>: Represents multiple values (a stream of data).

2. Router Functions & Annotated Controllers

  • Functional approach: RouterFunction and HandlerFunction.
  • Annotation-based approach: @RestController with @GetMapping, @PostMapping, etc.

3. WebClient

  • A non-blocking alternative to RestTemplate for making HTTP requests.etc.

Setting Up WebFlux in a Spring Boot Project

step 1: Add Dependencies

To use WebFlux, add the following dependencies to pom.xml:

<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-data-mongodb-reactive</artifactId>
</dependency>
<dependency>
     <groupId>io.projectreactor</groupId>
     <artifactId>reactor-core</artifactId>
</dependency>

Step 2: Create an Entity

Below is an Entity file of Reactive MongoDB:

@Document(“products”)
public class Product {
 
@Id
private String id;
private String name;
private Long price;
 
           // Getters and setters
}

Step 3: Create a Reactive Repository

Below is the repository of ReactiveMongoRepository type, which provides CRUD operations for the Users collection in MongoDB:

@Repository
public interface UserRepository extends ReactiveMongoRepository<Users,String> {

}

Step 4: Implement the Service Layer

The service layer will interact with the UserRepository and provide business logic methods for handling users:

@Service
public class ProductService {

private final ProductRepository productRepository;

@Autowired
public ProductService(ProductRepository productRepository) {
    this.productRepository = productRepository;
}

public Mono<Product> save(Product product) {
   return productRepository.save(product);
}

public Mono<Product> getProductById(String id) {
   return productRepository.findById(id);
}

public Flux<Product> getAllProducts() {
    return productRepository.findAll();
}
}

Step 5: Create a Reactive REST Controller

Below is an example of a WebFlux-based REST API that returns a stream of data, for handling asynchronous, non-blocking requests using an annotation-based approach.:

@RestController
@RequestMapping(“/api/products”)
public class ProductController {
private final ProductService productService;

@Autowired
public ProductController(ProductService productService) {
    this.productService = productService;
}

@PostMapping(“/save”)
public Mono<Product> saveProduct(@RequestBody Product product) {
   return productService.save(product);
}

@GetMapping(“/{id}”)
public Mono<Product> getProductById(@PathVariable String id) {
   return productService.getProductById(id);
}

@GetMapping(“/all”)
public Flux<Product> getAllProducts() {
   return productService.getAllProducts();
}
}

Step 6: Application property

Here we can see an Application.properties file for your Spring WebFlux application using MongoDB and reactive programming. This configuration will set up MongoDB and provide necessary configurations for your application.

spring.application.name=webflux-demo

spring.data.mongodb.database=webflux_db
spring.data.mongodb.uri=mongodb://localhost:27017/webflux_db
server.port=8080

Step 7: Using WebClient to Consume APIs

WebClient is a non-blocking HTTP client in WebFlux:

WebClient webClient = WebClient.create(“http://localhost:8080”);

Mono<Product> productMono = webClient.get()
.uri(“/api/products/1”)
.retrieve()
.bodyToMono(Product.class);

productMono.subscribe(
product -> System.out.println(“Product found: ” + product),
error -> System.out.println(“Error occurred: ” + error.getMessage())
);

Testing WebFlux APIs using Postman

  1. Open Postman and send a GET request to http://localhost:8080/api/products/all.
  2. Expected Response (Streaming Data):

[
{ “id”: “1”, “name”: “Laptop”, “price”: 1000 },
{ “id”: “2”, “name”: “Phone”, “price”: 500 }
]

    3. For single product retrieval: GET http://localhost:8080/api/products/1.

Conclusion

Spring WebFlux provides a powerful framework for developing reactive applications in Java. By leveraging non-blocking, event-driven programming, developers can build highly scalable and responsive microservices.

Need expert WebFlux development? Swarck Infolabs specializes in Java-based reactive solutions. Contact us today!

No comment

Leave a Reply

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