Understanding Spring WebFlux: Reactive Web Development with Spring
This article introduces Spring WebFlux as a reactive, non‑blocking web framework for Java, explains the concepts of reactive programming, compares it with Spring MVC, and provides practical code examples—including Mono/Flux usage, routing, and handlers—to help developers build and run a WebFlux application with Spring Boot.
Spring WebFlux is the reactive‑programming style web framework introduced in Spring 5.0, capable of running on Netty, Undertow, or any Servlet container version 3.1 and above, and can be used alongside or instead of Spring MVC.
What is "reactive"? Reactive programming allows an API call to return immediately without blocking; the system processes other tasks while waiting for data, improving throughput by utilizing CPU resources only when data arrives.
Reactive programming defines standards for asynchronous, non‑blocking stream processing, similar to Java 8's Stream API, and includes specifications for the runtime environment and network protocols.
Spring WebFlux Reactive API is built on the Reactor project and provides two core types: Mono<T> for single‑item streams and Flux<T> for multi‑item streams.
// Mono generally works with a single object
Mono<Person> person = personDao.getPerson(personId);
// Flux generally works with multiple objects
Flux<Person> people = personDao.listAllPeople();WebFlux can also interoperate with other reactive libraries such as RxJava.
Choosing Spring MVC or Spring WebFlux depends on project requirements: if an existing Spring MVC project works well and uses blocking libraries, stay with MVC; otherwise, WebFlux offers non‑blocking I/O, flexible server choices (Netty, Tomcat, Jetty, Undertow), functional routing, and various reactive programming models (Reactor, RxJava).
Key considerations include the prevalence of blocking APIs (e.g., JDBC), team expertise with reactive concepts, and the need for higher concurrency in microservices.
Concurrency Model Spring MVC uses a thread‑per‑request model with blocking I/O, limiting throughput by the number of threads. WebFlux leverages Netty’s NIO event‑loop model, requiring only a few worker threads and achieving higher request concurrency without blocking.
WebFlux Code Example
First, add the WebFlux starter dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>Define a simple POJO:
public class Person {
private Integer id;
private Integer age;
private String name;
}Create a functional router:
@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 (service layer):
@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());
}
}Running the application with Spring Boot defaults to Netty, confirming the reactive server via startup logs. Accessing http://localhost:8080/person/1 demonstrates a working WebFlux endpoint.
END
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.