Introduction to Spring WebFlux and Reactive Programming
This article introduces Spring WebFlux as a reactive, non‑blocking web framework built on Reactor, explains the concepts of reactive programming, compares it with traditional Spring MVC, and provides practical code examples for building and running a WebFlux application with Spring Boot.
Spring WebFlux is a reactive‑programming style web framework introduced in Spring 5.0 that builds on the Spring Framework and Spring MVC and can run on Netty, Undertow, or any servlet container version 3.1 and above.
Reactive programming means that API calls do not block the thread while waiting for data; instead, the system is notified when data arrives, allowing the CPU to perform other work and improving overall throughput.
The reactive model defines a standard for asynchronous, stream‑based programming, similar to Java 8's Stream API, and includes specifications for the runtime environment (JVM, JavaScript) and network protocols.
Spring WebFlux is based on the open‑source Reactor project and offers two core types: Mono<T> for handling a single element and Flux<T> for handling multiple elements.
// Mono for a single object
Mono<Person> person = personDao.getPerson(personId);
// Flux for multiple objects
Flux<Person> people = personDao.listAllPeople();Although built on Reactor, WebFlux can interoperate with other reactive libraries such as RxJava.
When deciding between Spring MVC and Spring WebFlux, consider whether the existing project already works well with MVC, whether most third‑party libraries are blocking, and whether the application will benefit from non‑blocking I/O. WebFlux offers many deployment options (Netty, Tomcat, Jetty, Undertow, servlet containers) and can be used with either annotation‑based controllers or functional routing.
In terms of concurrency, MVC uses a thread‑per‑request model with a fixed thread pool, which limits throughput due to blocking I/O. WebFlux, by contrast, runs on an event‑loop model (e.g., Netty) with a small number of worker threads, allowing higher concurrency and better CPU utilization.
Below is a minimal Spring Boot WebFlux setup. First, add the dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>Define a simple domain object:
public class Person {
private Integer id;
private Integer age;
private String name;
}Configure functional routing:
@Configuration
public class PersonRouter {
@Resource
private PersonHandler personHandler;
@Bean
public RouterFunction<ServerResponse> personRoutes() {
return RouterFunctions.route()
.GET("/person/{id}", RequestPredicates.accept(MediaType.APPLICATION_JSON), personHandler::getPerson)
.GET("/person", RequestPredicates.accept(MediaType.APPLICATION_JSON), personHandler::listPeople)
.POST("/person", personHandler::createPerson)
.build();
}
}Implement the handler using reactive types:
@Component
public class PersonHandler {
@Resource
private PersonRepository personDao;
public Mono<ServerResponse> listPeople(ServerRequest request) {
Flux<Person> people = personDao.listAllPeople();
return ServerResponse.ok()
.contentType(MediaType.APPLICATION_JSON)
.body(people, Person.class);
}
public Mono<ServerResponse> createPerson(ServerRequest request) {
Mono<Person> person = request.bodyToMono(Person.class);
return ServerResponse.ok().build(personDao.savePerson(person));
}
public Mono<ServerResponse> getPerson(ServerRequest request) {
int personId = Integer.parseInt(request.pathVariable("id"));
return personDao.getPerson(personId)
.flatMap(p -> ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).bodyValue(p))
.switchIfEmpty(ServerResponse.notFound().build());
}
}When the application starts, Spring Boot uses Netty by default; accessing http://localhost:8080/person/1 demonstrates that the WebFlux service is running correctly.
Architecture Digest
Focusing on Java backend development, covering application architecture from top-tier internet companies (high availability, high performance, high stability), big data, machine learning, Java architecture, and other popular fields.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.