Getting started with Spring Webflux

Reading Time: 3 minutes

Overview

Hello everyone, In this blog, I am going to discuss an introduction to webflux.

The original web framework included in the Spring Framework, Spring Web MVC, was purpose-built for the Servlet API and Servlet containers. The reactive-stack web framework, Spring
WebFlux was added later in version 5.0.

What is Spring Webflux?

Spring Webflux is fully non-blocking and supports Reactive Streams back pressure. It runs on such servers as Netty, Undertow, and Servlet 3.1+ containers. WebFlux framework uses new router function features to apply functional programming to the web layer and bypass declarative controllers and RequestMappings.

What is the Reactive Programming Paradigm?

The term, “reactive,” refers to programming models that are built around reacting to
change — network components reacting to I/O events, UI controllers reacting to mouse events, and
others. In that sense, non-blocking is reactive, because, instead of being blocked, we are now in the
mode of reacting to notifications as operations complete or data becomes available.

There is also another important mechanism that we on the Spring team associate with “reactive”
and that is non-blocking back pressure. In synchronous, imperative code, blocking calls serve as a
natural form of back pressure that forces the caller to wait. In non-blocking code, it becomes
important to control the rate of events so that a fast producer does not overwhelm its destination.

Reactive Streams is a small spec (also adopted in Java 9) that defines the interaction between
asynchronous components with back pressure. For example a data repository (acting as Publisher)
can produce data that an HTTP server (acting as Subscriber) can then write to the response. The
main purpose of Reactive Streams is to let the subscriber control how quickly or how slowly the
publisher produces data.

Blocking Request

In a conventional MVC application, whenever a request reaches the server, a servlet thread is being created and delegated to worker threads to perform various operations like I/O, database processing, etc. While the worker threads are busy completing their processes, the servlet threads enter a waiting state due to which the calls remain blocked. This is blocking or synchronous request processing.

Non-Blocking Request

In case of a non-blocking request processing, there is no thread in the waiting or blocking condition. The reactive programming model is based on observable streams and callback functions. Thus, when a response or a part of the response is ready the respective subscribers receive a callback. That means, the servlet thread can invoke various workers, and then it becomes free to process another request. Because of this, the underlying server can have a very small number of threads in the pool and the application can still process a large number of requests.

Understanding Mono and Flux in Spring Webflux

Mono

Mono is the Reactive equivalent of CompletableFuture type and allows to provide a consistent API for handling single and multiple elements in a Reactive way.

Mono<String> mono = Mono.just("Shivam");
Mono<Object> monoEmpty = Mono.empty();
Mono<Object> monoError = Mono.error(new Exception());

Flux

Flux is a reactor streams publisher that publishes 0 to N elements. That means a Flux will always emit 0 or up to infinity elements, or send an error signal if something goes wrong.

Flux<Integer> flux = Flux.just(1, 2, 3, 4);
Flux<String> fluxString = Flux.fromArray(new String[]{"A", "B", "C"});
Flux<String> fluxIterable = Flux.fromIterable(Arrays.asList("A", "B", "C"));
Flux<Integer> fluxRange = Flux.range(2, 5);
Flux<Long> fluxLong = Flux.interval(Duration.ofSeconds(10));

// To Stream data and call subscribe method
List<String> dataStream = new ArrayList<>();
Flux.just("X", "Y", "Z")
    .log()
    .subscribe(dataStream::add);

Spring Webflux Config

The WebFlux Java configuration declares the components that are required to process requests
with annotated controllers or functional endpoints, and it offers an API to customize the
configuration. That means you do not need to understand the underlying beans created by the Java
configuration. However, if you want to understand them, you can see them in
WebFluxConfigurationSupport or read more about what they are in Special Bean Types.
For more advanced customizations, not available in the configuration API, you can gain full control
over the configuration through the Advanced Configuration Mode.

Enabling WebFlux Config

You can use the @EnableWebFlux annotation in your Java config, as the following example shows:

@Configuration
@EnableWebFlux
public class WebConfig {
}

The preceding example registers a number of Spring WebFlux infrastructure beans and adapts to
dependencies available on the classpath — for JSON, XML, and others.

Conclusion

In conclusion, in this blog, we have learned about Spring Webflux. I will be covering more topics on spring webflux in my future blogs, stay connected. Happy learning 🙂

For more, you can refer to the webflux documentation: https://docs.spring.io/spring-framework/docs/current/reference/html/web-reactive.html

For a more technical blog, you can refer to the Knoldus blog: https://blog.knoldus.com/

Written by 

Hello! Currently, I am Software Consultant at Knoldus Inc. I have completed my B.Tech from Abdul Kalam Technical University. Right now I am focusing on JAVA Frameworks. Apart from that my hobbies are playing guitar and listening to music.

Leave a Reply