Features of Spring Webflux

Reading Time: 3 minutes

Parallel to Spring MVC, Spring WebFlux fully supports non-blocking reactive streams. It utilizes Netty as an internal server to run reactive applications, and it supports the back pressure notion. If you are comfortable with the Spring MVC programming model, working with webflux will be simple for you.

Project Reactor serves as the reactive library for Spring WebFlux. All of Reactor’s operators support non-blocking back pressure because it is a Reactive Streams library. Spring and it work closely together to develop it.

Your controllers will return monos and fluxes when you call reactive APIs and functions in Spring WebFlux. An API that returns a mono or a flux will respond instantly when it is called. When the results of the function call become ready, they will be sent to you via the mono or flux.

Mono: Returns 0 or 1 element.

Mono<String> mono = Mono.just("Alex");
Mono<String> mono = Mono.empty();

Flux: Returns 0…N elements. A Flux can be endless, meaning that it can keep emitting elements forever. Also, it can return a sequence of elements and then send a completion notification when it has returned all of its elements.

Flux<Integer> flux = Flux.just(1,2,3,4);
Flux<String> flux = Flux.fromArray(new String[]{"A", "B", "C"});
Flux<String> flux = Flux.fromIterable(Arrays.asList("A", "B","C"));

Salient Features of Spring WebFlux

Router functions

The @RequestMapping and @Controller annotation styles used in standard Spring MVC have a functional replacement called RouterFunction.

Instead of developing a full router function, you can define routes using the RouterFunctions.route() method. Routes can be built in any configuration class because they are registered as Spring beans.

WebClient

The responsive web client for WebFlux was created using the well-known RestTemplate. It is a synchronous and asynchronous operation-supporting interface that serves as the primary entry point for web requests. Most reactive backend-to-backend communication uses WebClient.

By using Maven to import the following standard WebFlux dependencies, you can build and produce a WebClient instance:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-webflux</artifactId>
</dependency>

Reactive Steam API

An imported set of functions called Reactive Stream API enables more intelligent stream data flow. It contains built-in support for back-pressure and asynchronous processing to make sure the programme uses both computer and component resources as effectively as possible.

Reactive Stream API has four main interfaces:

Publisher

events to associated Subscribers in response to their requests. serves as a focal point where subscribers may keep an eye out for events.

Subscriber

receives and handles events that the Publisher emits. Multiple Subscribers can connect to the same Publisher and react to the same event in various ways.

Subscription

Specifies the connection between the specified Publisher and Subscriber. Only one Publisher may be connected to each Subscriber.

Processor

Represents the processing stage of the subscriber.

Servers

The non-Servlet runtimes Netty and Undertow as well as the containers Tomcat, Jetty, and Servlet 3.1+ all support WebFlux. For async and non-blocking designs, Netty is the most popular choice, so WebFlux will utilize that by default. Changes to your Maven or Gradle build tools make it simple to switch between these server configurations.

This gives WebFlux a wide range of compatibility with technologies and makes it simple to integrate it with existing infrastructure.

Concurrency Model

Due to its non-blocking design, WebFlux employs a different concurrent programming style than Spring MVC.

Spring MVC employs a sizable thread pool to keep things flowing even when threads are stalled since it anticipates that they will. Due to the need for the computer hardware to support many spinning threads at once, MVC requires additional resources.

Since it is assumed that you would never need to delegate work to avoid a blocker, WebFlux instead makes use of a small thread pool. These fixed-number threads, often known as event loop workers, process incoming requests more quickly than MVC threads. This indicates that WebFlux makes better use of computer resources as active threads are always active.

Spring WebFlux Security

To build authentication and authorization methods, WebFlux makes advantage of Spring Security. Requests can be automatically rejected by Spring Security if they match certain criteria, such as origin or request type, or they can be checked against an authenticated list of users using WebFilter.

@EnableWebFluxSecurity
public class HelloWebFluxSecurityConfig {
    @Bean
    public MapReactiveUserDetailsService userDetailsService() {
        UserDetails user = User.withDefaultPasswordEncoder()
            .username("user")
            .password("user")
            .roles("USER")
            .build();
        return new MapReactiveUserDetailsService(user);
    }
}

Conclusion

Applications that use Spring WebFlux or Reactive non-blocking applications typically do not run more quickly. The ability to scale an application with a limited, fixed number of threads and lower memory requirements while utilizing the available processing power is its primary advantage. Because they can scale predictably, it frequently increases a service’s load-time resilience.

Written by 

Mohd Uzair is a Software intern at Knoldus. He is passionate about java programming. He is recognized as a good team player, a dedicated and responsible professional, and a technology enthusiast. He is a quick learner & curious to learn new technologies. His hobbies include watching movies, surfing youtube, playing video games.

Leave a Reply