Java, Spring Boot

How To Use WebFlux with Spring Boot

Using WebFlux with Spring Boot is straightforward and may not require changes when moving from Spring MVC. We will still use the same set of annotations like RestController and RequestMapping, to name a few. However, we use WebFlux to tap the non-blocking I/O operations for better performance. Therefore, we still need to change the codes we developed for Spring MVC to follow the reactive programming paradigm to take advantage of the benefits.

Spring MVC And Spring WebFlux – What is the difference?

In a nutshell, Spring MVC works with thread-per-request operations, which are synchronous. While Spring WebFlux uses an event loop and allows for non-blocking and asynchronous operations in Spring Boot.

Although Spring Boot now has the async annotation@Async – to make an operation asynchronous, e.g., HTTP GET, it still uses a thread for each incoming request.

When Using Them

Spring MVC and WebFlux are mutually exclusive. Meaning, we cannot use both Spring MVC and WebFlux with Spring Boot simultaneously. We can use either dependency in our pom.xml.

When we use Spring WebFlux with Spring Boot, we will have the following dependency.

On the other hand, we use the following dependency with Spring Boot when using Spring MVC.

Asynchronous Operations With Spring WebFlux

To turn some public methods in a controller to asynchronous, we need to return values wrapped in either Mono or Flux. We use Mono when we return single values and Flux when we produce a collection of values. Consider the following examples.

These endpoints are now asynchronous. For example, when we want to retrieve a single Person’s data, we use HTTP GET /demo/1. On the other hand, when we want to get all Person data, we use HTTP GET /demo

When we return data to client applications, we need to convert them using static methods available in the Mono and Flux classes. For instance, to produce a collection of PersonDTO as Flux, we use the fromIterable method.

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like