Search⌘ K

Reactive Controller

Explore how to create a reactive controller in Spring WebFlux that uses Flux to retrieve quotes from MongoDB efficiently. Understand the use of reactive streams, how to simulate processing delays to compare reactive and MVC approaches, and implement pagination to handle large datasets with optimal performance and resource use.

Controller’s code

Let’s focus now on the most important part of our backend application: the reactive controller. First, let’s see the full code source, and then we’ll navigate through the different parts.

Java
package com.thepracticaldeveloper.reactiveweb.controller;
import com.thepracticaldeveloper.reactiveweb.domain.Quote;
import com.thepracticaldeveloper.reactiveweb.repository.QuoteMongoReactiveRepository;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import java.time.Duration;
@RestController
public class QuoteReactiveController {
private static final int DELAY_PER_ITEM_MS = 100;
private final QuoteMongoReactiveRepository quoteMongoReactiveRepository;
public QuoteReactiveController(final QuoteMongoReactiveRepository quoteMongoReactiveRepository) {
this.quoteMongoReactiveRepository = quoteMongoReactiveRepository;
}
@GetMapping("/quotes-reactive")
public Flux<Quote> getQuoteFlux() {
return quoteMongoReactiveRepository.findAll().delayElements(Duration.ofMillis(DELAY_PER_ITEM_MS));
}
@GetMapping("/quotes-reactive-paged")
public Flux<Quote> getQuoteFlux(final @RequestParam(name = "page") int page,
final @RequestParam(name = "size") int size) {
return quoteMongoReactiveRepository.findAllByIdNotNullOrderByIdAsc(PageRequest.of(page, size))
.delayElements(Duration.ofMillis(DELAY_PER_ITEM_MS));
}
}

If you’re familiar with Spring controllers and their annotations, you’ll quickly find out that the only part of the code that seems different is the Flux object we’re returning as a result of the methods. In Spring MVC, we would probably return a Java collection (e.g., List) instead.

Let’s park the delayElements ...