Reactive Controller

Learn how to create a reactive controller.

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.

Press + to interact
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 ...