Why Choose Spring WebFlux? A Deep Dive into Reactive Backend Development
This article explains Spring WebFlux's reactive programming model, compares it with Spring MVC, describes its concurrency advantages, and provides complete code examples for building a reactive Spring Boot application, helping developers decide when to adopt WebFlux.
Spring WebFlux Overview
Spring WebFlux is the reactive‑programming style web framework introduced in Spring 5.0. It builds on the Spring Framework and Spring MVC and can run on Netty, Undertow, or any Servlet 3.1+ container.
What Is “Reactive”?
Reactive means non‑blocking: an API call returns immediately and the caller is notified when data arrives, allowing the CPU to perform other work and increasing system throughput. Reactive programming defines a standard for asynchronous, stream‑based code, similar to Java 8’s Stream API.
Spring WebFlux Reactive API
The framework is based on the open‑source Reactor project and provides two core types: Mono (for a single value) and Flux (for multiple values).
// Mono for a single object
Mono<Person> person = personDao.getPerson(personId);
// Flux for many objects
Flux<Person> people = personDao.listAllPeople();Choosing Spring MVC or Spring WebFlux
Both can be used in the same project. If you already have a stable Spring MVC application and most third‑party libraries are blocking, staying with MVC is fine. WebFlux offers many deployment options (Netty, Tomcat, Jetty, Undertow, Servlet containers) and supports functional routing with @Controller or RouterFunctions.
If you prefer Java 8 lambda style and lightweight micro‑services, WebFlux is a good fit.
In a micro‑service architecture you can mix MVC and WebFlux; both use @Controller annotations.
Evaluate whether your code uses many blocking APIs (e.g., JDBC); if so, WebFlux may not bring benefits.
For many external calls, consider the reactive WebClient to return reactive results from a controller.
Concurrency Model
Spring MVC uses a thread‑per‑request model with a thread pool, limiting throughput by the number of threads. WebFlux, built on Netty’s NIO, uses a few event‑loop workers to handle many concurrent requests, improving CPU utilization and overall throughput.
WebFlux Code Example
Add the 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;
}Configure functional routes:
@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();
}
}Handler implementation:
@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 WebFlux uses Netty as the default HTTP server. Accessing http://localhost:8080/person/1 demonstrates the reactive endpoint in action.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Backend Technology
Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!
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.
