#
Spring WebFlux: Flux Stream Example
This tutorial shows you how to use Flux with Spring Boot WebFlux.
Reactive Streams gives us a common API for Reactive Programming in Java. For more information about Reactive Programming you can take a look at the Reactive manifesto as well.
Reactive programming is about building asynchronous, non-blocking and event-driven applications that can easily scale. Each event is published to subscribers while ensuring that the subscribers are never overwhelmed.
Spring 5 Framework introduced Reactor as an implementation for the Reactive Streams specification (by introducing a brand new reactive framework called Spring WebFlux). Reactor is a next-gen Reactive library for building non-blocking applications on the JVM. Reactor is a fourth-generation Reactive library for building non-blocking applications on the JVM based on the Reactive Streams Specification.
Reactor Provides two main types called Flux and Mono. Both of these types implement the Publisher interface provided by Reactive Streams. Flux is used to represent a stream of 0..N elements and Mono is used to represent a stream of 0..1 element.
For creating an example using the Flux stream type with Spring Flux framework, you have to create a Spring Boot application. In my case I used Spring Initializr :
You have to select as dependency "Reactive Web", generate the project and open it in your IDE tool. In my case, I used Spring Tool Suite. Your POM must look like this:
Maven will download the following dependencies automatically:
Run the Spring FluxWebFlux Application in order to see if all works good. If not it is possible not to have the Maven Repository OK and you must run the following commands:
cd <project_home>
mvn dependency:purge-local-repository
Once the project is running without errors add the code to get the Spring FluxWebFlux Application main class like this:
package com.example.FluxWebFlux;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import reactor.core.publisher.Flux;
@SpringBootApplication
public class FluxWebFluxApplication {
public static void main(String[] args) {
Flux<integer> fluxStream = Flux.just(10, 20, 30, 40);
SpringApplication.run(FluxWebFluxApplication.class, args);
fluxStream.subscribe(val ->
{
System.out.println("Subscriber uses the values from publisher: "+val*10);
});
}
}
Run the Spring FluxWebFlux Application and you will see something like this:
In this picture you can see that a Flux Stream is created and a consumer is created and read the content of the Stream. The consumer print the number received from the producer multiplied by 10. This is a type of programming based on event.
Info
Mono and Flux are both implementations of the Publisher interface.