在前几期中,我们从 Spring 核心到 Spring Boot 的各个模块,逐步揭示了 Spring 生态的丰富功能。随着响应式编程(Reactive Programming)的兴起,Spring WebFlux 提供了基于事件驱动和高并发处理的 Web 框架,成为 Spring 5 的重要创新。本篇将深入 Spring WebFlux 的源码,剖析其响应式模型与请求处理流程。
1. Spring WebFlux 的核心概念
Spring WebFlux 是 Spring 的响应式 Web 框架,与传统的 Spring MVC 基于 Servlet 的阻塞模型不同,它基于 Reactor 库,支持非阻塞 I/O。核心概念包括:
- Mono:表示单个值的异步流。
- Flux:表示多个值的异步流。
- WebFlux Server:基于 Netty、Undertow 或 Servlet 3.1+ 的容器。
- HandlerFunction:处理请求的函数式编程模型。
- RouterFunction:路由请求到处理函数。
Spring WebFlux 支持两种编程模型:注解式(类似 MVC)和函数式。
2. Spring WebFlux 的基本配置
一个简单的 Spring Boot WebFlux 配置:
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
@RestController
@RequestMapping("/api")
public class UserController {
@GetMapping("/users")
public Flux<String> getUsers() {
return Flux.just("User1", "User2", "User3");
}
@GetMapping("/user/{id}")
public Mono<String> getUser(@PathVariable String id) {
return Mono.just("User: " + id);
}
}
@SpringBootApplication
自动配置 WebFlux。- 返回
Flux
或Mono
,支持响应式流。
3. WebFlux 的自动装配
Spring Boot 通过 spring-boot-starter-webflux
启用 WebFlux:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.boot.autoconfigure.webflux.WebFluxAutoConfiguration
WebFluxAutoConfiguration
:
@Configuration
@ConditionalOnWebApplication(type =<