响应式控制器
使用 WebFlux 构建非阻塞端点
响应式控制器 是 CoddyKit 上的免费 Spring Boot 4 Microservices & REST APIs 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Spring Boot 4 Microservices & REST APIs 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Spring Boot 4 Microservices & REST APIs 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Reactive Web Endpoints
With WebFlux you write @RestController classes just like in Spring MVC, but methods return reactive types instead of plain objects.
- Return
Mono<T>for a single resource - Return
Flux<T>for a collection or stream
Returning a Mono
A handler returning Mono resolves to a single JSON object. The framework subscribes for you.
@RestController
@RequestMapping("/users")
public class UserController {
@GetMapping("/{id}")
public Mono<User> getUser(@PathVariable String id) {
return userService.findById(id);
}
}Returning a Flux
A handler returning Flux serializes to a JSON array by default.
@GetMapping
public Flux<User> getAllUsers() {
return userService.findAll();
}No Blocking Allowed
Inside reactive handlers you must not call blocking code. Return the publisher and let the chain stay reactive.
// BAD: blocks the event loop
@GetMapping("/bad")
public User bad() {
return userService.findById("1").block();
}
// GOOD: stays reactive
@GetMapping("/good")
public Mono<User> good() {
return userService.findById("1");
}Path and Query Params
Binding annotations work the same as in MVC: @PathVariable, @RequestParam, and @RequestBody.
@GetMapping("/search")
public Flux<User> search(@RequestParam String name) {
return userService.findByName(name);
}Accepting a Reactive Body
A POST handler can accept a Mono request body, keeping the whole flow non-blocking.
@PostMapping
public Mono<User> create(@RequestBody Mono<User> body) {
return body.flatMap(userService::save);
}Setting Status Codes
Use @ResponseStatus or wrap results in ResponseEntity within a Mono.
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public Mono<User> create(@RequestBody Mono<User> body) {
return body.flatMap(userService::save);
}ResponseEntity in a Mono
To control headers and status dynamically, return Mono<ResponseEntity<T>>.
@GetMapping("/{id}")
public Mono<ResponseEntity<User>> getUser(@PathVariable String id) {
return userService.findById(id)
.map(ResponseEntity::ok)
.defaultIfEmpty(ResponseEntity.notFound().build());
}Streaming with Server-Sent Events
Set the content type to text/event-stream to stream a Flux to the client over time.
@GetMapping(value = "/stream",
produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<Long> stream() {
return Flux.interval(Duration.ofSeconds(1));
}Error Handling
Use onErrorResume to map errors to a fallback publisher, or a @ControllerAdvice for global handling.
@GetMapping("/{id}")
public Mono<User> getUser(@PathVariable String id) {
return userService.findById(id)
.onErrorResume(e -> Mono.error(
new ResponseStatusException(HttpStatus.NOT_FOUND)));
}The Netty Server
WebFlux runs on Netty by default — an event-loop server with a small fixed thread pool. This is why blocking calls are so harmful: blocking one thread stalls many requests.
Quick Check
Test your understanding of reactive controllers.
Recap
You learned how to build reactive endpoints:
@RestControllermethods returnMonoorFlux- Never call
block()inside a handler - Use
ResponseEntityin a Mono for dynamic status - Stream with
text/event-stream
常见问题解答
「响应式控制器」课时是免费的吗?
是的 — 「响应式控制器」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Spring Boot 4 Microservices & REST APIs 课程的其余内容,请升级到 CoddyKit PRO。 Spring Boot 4 Microservices & REST APIs 课程共包含 4 节课。
「响应式控制器」这节课中我会学到什么?
使用 WebFlux 构建非阻塞端点 你通过在浏览器中直接运行的动手代码来练习 Spring Boot 4 Microservices & REST APIs,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Spring Boot 4 Microservices & REST APIs 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Spring Boot 4 Microservices & REST APIs 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。
「响应式控制器」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Spring Boot 4 Microservices & REST APIs 课中编写并运行代码吗?
能。每节 Spring Boot 4 Microservices & REST APIs 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。