WebFlux_0">三、WebFlux
Blocking Web vs. Reactive Web
Blocking Web (Servlet) and Reactive Web (WebFlux) have significant differences in several aspects.
1. Front Controller
- Servlet-Blocking Web: Uses
DispatcherServlet
as the front controller to handle all HTTP requests. - WebFlux-Reactive Web: Uses
DispatcherHandler
as the front controller to handle all HTTP requests.
2. Handler
- Servlet-Blocking Web: Uses
Controller
as the handler. - WebFlux-Reactive Web: Uses
WebHandler
orController
as the handler.
3. Request and Response
- Servlet-Blocking Web: Uses
ServletRequest
andServletResponse
. - WebFlux-Reactive Web: Uses
ServerWebExchange
, along withServerRequest
andServerResponse
.
4. Filters
- Servlet-Blocking Web: Uses Filter (e.g., HttpFilter).
- WebFlux-Reactive Web: Uses
WebFilter
.
5. Exception Handlers
- Servlet-Blocking Web: Uses
HandlerExceptionResolver
to handle exceptions. - WebFlux-Reactive Web: Uses
DispatchExceptionHandler
to handle exceptions.
6. Web Configuration
- Servlet-Blocking Web: Configured via
@EnableWebMvc
. - WebFlux-Reactive Web: Configured via
@EnableWebFlux
.
7. Custom Configuration
8. Return Types
- Servlet-Blocking Web: The return type can be any object.
- WebFlux-Reactive Web: The return type can be a
Mono
, aFlux
, or any object.
9. Sending REST Requests
- Servlet-Blocking Web: Uses
RestTemplate
to send REST requests. - WebFlux-Reactive Web: Uses
WebClient
to send REST requests.
Core Difference Between Blocking and Reactive Models
Blocking Model (Servlet): Each request is handled by a dedicated thread, which waits for operations to complete (such as database queries or IO operations). This model can lead to thread exhaustion under high concurrency, affecting system performance.
Reactive Model (WebFlux): Uses a non-blocking IO model with a small number of threads handling many requests. It leverages callback mechanisms, event-driven architecture, and asynchronous non-blocking IO for efficient resource utilization and high concurrency handling. Key features of the reactive programming model include:
- Non-blocking Operations: Operations do not block the current thread, allowing it to continue processing other tasks.
- Callback Mechanism: Handles subsequent steps through callback mechanisms once an operation completes.
- Event-driven Architecture: Processes requests based on an event-driven approach.
This model is more efficient in resource usage and is suitable for scenarios requiring high concurrency and large traffic volumes.
Summary
The choice between a blocking or reactive web framework depends on specific application scenarios and requirements. If the application is primarily I/O-intensive with high concurrency needs, then WebFlux is a more suitable choice; if it involves CPU-intensive tasks, the traditional Servlet model might be more appropriate.