Spring WebFlux Tutorial - Overview
Overview
In this tutorial we will be looking at Spring WebFlux overview and it's components.
Spring WebFlux Tutorial :
Spring WebFlux, like SpringMVC and Node.js provides reactive, async, non-blocking programming support for web applications in an annotated Controller style.
Let's first understand the basic concept to understand the Spring WebFlux.
What is reactive programming?
The concept "reactive" denotes to programming models that are designed to react to changes. It is based on the publisher-subscriber model (observer pattern). In a reactive programming technique, we submit a request for a resource and then begin doing other things. When the data is ready, we receive a notification along with a data inform about the call back function. In the callback function, we process the response in accordance with the needs of the application/user.
WebFlux was added in Spring 5 as a reactive alternative to Spring MVC, with added support for:
Non-blocking threads
Concurrent threads which finish their assigned work without waiting for earlier tasks to finish.Reactive Stream API
A standardised tool providing non-blocking backpressure options for asynchronous stream processing.Asynchronous data processing
When data is processed in the background as well as the user can continue to even use the app without disruption.
What is WebClient?
WebClient is WebFlux's reactive web client, based on the well-known RestTemplate. It is an interface that serves as the primary entry point for web requests and allows both synchronous and asynchronous actions. WebClient is often used for reactive backend-to-backend interaction.
WebClient client = WebClient.create();
What are the Reactive Steam API's?
The Reactive Stream API is an integrated set of functions that enables better stream data flow. It includes support for back-pressure and asynchronous processing, ensuring that the programm makes the most use of both system and it's resources.
Reactive Stream API has 4 main interfaces:
Publisher
It generates a series of events to subscribers based on the demand received from it's subscribers. A publisher can service multiple subscribers.public interface Publisher { public void subscribe(Subscribers); }
Subscriber
A subscriber can subscribe to a publisher, specify the amount of data the publisher may send, and then process the data. Subscribers can be programmed to respond in a variety of ways, including:- onNext, when it receives the next event.
- onSubscribe, when a new subscriber is added.
- onError, when an error occurs with another subscriber.
- onComplete, when another subscriber finishes its task.
public interface Subscriber { public void onSubscribe(Subscription s); public void onNext(T t); public void onError(Throwable t); public void onComplete(); }
Subscription
A one-to-one relation between a Publisher and a Subscriber. Which can only be used by one Subscriber at a time. It's being used to both signal and cancel data demand (and support resource cleanup).public interface Subscription
{
public void request(long n);
public void cancel();
}
Processor
A processor comes in the middle between a publisher and a subscriber, allowing for data transformation.public interface Processor extends Subscriber, Publisher
{
}
What is Project Reactor in Spring WebFlux?
Based on the Reactive Streams specification, Project Reactor provides a Reactive library.
Reactor provides two types:
Mono
It implements Publisher and returns zero items or a single item ( 0..1 ).
Since we only return one employee, we enclose a single Employee resource in a Mono.@GetMapping("/{id}") private Mono<Employee> getEmployeeById(@PathVariable String id) { return employeeRepository.findEmployeeById(id); }
Flux
It implements Publisher and returns zero or more items ( 0.. N ).
We use a Flux of type Employee for the collection resources because it returns 0..n elements.@GetMapping private Flux<Employee> getAllEmployees() { return employeeRepository.findAllEmployees(); }
Which databases are supported by Spring WebFlux?
Spring Data only supports reactive support for MongoDB, Cassandra, Redis, and Couchbase when it comes to database access. These are all NoSQL databases. However, NoSQL databases are not the only ones that can be reactive. The point is, the driver is the one who provides reactive support. It implies that the driver must be able to handle asynchronous actions. For the time being, there is no asynchronous JDBC driver for relational databases.
Blocking vs non-blocking (async) request processing
When a request is sent to the server in a conventional MVC application, a servlet thread is created. For I/O activities such as database access, it delegated the request to worker threads. While worker threads are occupied, the servlet thread (request thread) remains in a waiting state and is thus blocked. It is also referred to as synchronous request processing.
Because a server can only have a fixed number of request threads, the server's ability to process that number of requests at maximum server load is limited. It may affect performance and limit the server's capacity to be fully utilised.
There is no waiting thread in non-blocking or asynchronous request processing. In most cases, just one request thread receives the request.
- Every incoming request includes an event handler and call back information. The request thread forwards incoming requests to a thread pool (usually a small number of threads), which forwards the request to its handler function and quickly began processing new incoming requests from the request thread.
- Once the handler function is finished, one of the pool threads collects the response and passes it to the callback function.
- Threads' non-blocking feature helps in scaling application performance. A small number of threads ensures less memory use and context switching.