Spring WebFlux 与 Reactor Core
使用 Spring WebFlux 构建响应式 REST API,并操作 Reactor Core 中的 `Mono` 和 `Flux`。
Spring WebFlux 与 Reactor Core 是 CoddyKit 上的免费 Spring Boot 4 Complete Guide 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Spring Boot 4 Complete Guide 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Spring Boot 4 Complete Guide 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Reactive Web with Spring WebFlux
Welcome to Spring WebFlux! This framework is Spring's answer to building reactive, non-blocking web applications.
Unlike traditional Spring MVC which uses a servlet-based, blocking model, WebFlux is designed for concurrency and high throughput with fewer threads.
It's perfect for microservices and applications needing to handle many concurrent connections efficiently.
Diving into Reactor Core
At the heart of Spring WebFlux lies Reactor Core. Reactor is a reactive programming library that implements the Reactive Streams specification.
It provides two key types for handling asynchronous data streams:
Mono: For sequences of 0 or 1 item.Flux: For sequences of 0 to N items.
These types represent publishers that emit data, which subscribers then consume.
`Mono`: Zero or One Element
A Mono is a specialized Publisher that can emit at most one item, or complete without emitting any item, or emit an error.
Think of it as an asynchronous container for a single value. It's ideal for operations that return a single result, like fetching a user by ID or performing a single update.
Your First `Mono`
Let's see Mono in action. We create a Mono and then subscribe() to it. The subscribe() method triggers the data flow.
import reactor.core.publisher.Mono;
public class Main {
public static void main(String[] args) {
Mono<String> greetingMono = Mono.just("Hello, Mono!");
// Subscribe to the Mono to consume the data
greetingMono.subscribe(
data -> System.out.println(data), // onNext consumer
error -> System.err.println("Error: " + error), // onError consumer
() -> System.out.println("Mono completed.") // onComplete callback
);
}
}`Flux`: Zero to Many Elements
A Flux is a Publisher that can emit 0 to N items over time, and then optionally terminate with a completion signal or an error.
It's perfect for handling streams of data, like a list of products, real-time events, or database query results that return multiple rows.
Your First `Flux`
Here's an example of creating a Flux from a list of items. Just like Mono, you need to subscribe() to start the emission of data.
import reactor.core.publisher.Flux;
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> fruits = Arrays.asList("Apple", "Banana", "Cherry");
Flux<String> fruitFlux = Flux.fromIterable(fruits);
// Subscribe to the Flux to consume the data stream
fruitFlux.subscribe(
data -> System.out.println(data), // onNext consumer for each item
error -> System.err.println("Error: " + error), // onError consumer
() -> System.out.println("Flux completed.") // onComplete callback
);
}
}Building Reactive Endpoints
Spring WebFlux seamlessly integrates with Reactor Core's Mono and Flux. You can define your REST endpoints to return these reactive types.
When a WebFlux controller method returns a Mono or Flux, Spring handles the subscription and streaming of data automatically, allowing for non-blocking I/O.
Endpoint Returning `Mono`
Here's how you'd create a simple WebFlux endpoint that returns a Mono<String>. This endpoint would respond with a single string asynchronously.
Note: This code snippet is part of a Spring Boot application and cannot be run in isolation.
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
@RestController
public class HelloController {
@GetMapping("/hello-mono")
public Mono<String> getHelloMono() {
// Simulate a non-blocking operation that returns a single greeting
return Mono.just("Hello from Mono endpoint!");
}
}Endpoint Returning `Flux`
For endpoints that need to stream multiple items, you can return a Flux<T>. WebFlux will handle sending these items as they become available, often using Server-Sent Events (SSE).
Note: This code snippet is part of a Spring Boot application and cannot be run in isolation.
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import java.time.Duration;
@RestController
public class HelloController {
@GetMapping(value = "/hello-flux", produces = "text/event-stream")
public Flux<String> getHelloFlux() {
// Emit 5 items, one every second
return Flux.interval(Duration.ofSeconds(1))
.map(sequence -> "Item " + sequence + " from Flux!")
.take(5);
}
}Check Your Knowledge
Let's test your understanding of Spring WebFlux and Reactor Core.
Recap: WebFlux & Reactor Core
In this lesson, you've learned about the core components of reactive programming with Spring Boot:
- Spring WebFlux: The non-blocking web framework.
- Reactor Core: The underlying library providing reactive types.
Mono: For handling 0 or 1 data item.Flux: For handling 0 to N data items.
You also saw how to define reactive endpoints in WebFlux controllers by returning Mono and Flux.
用 AI 导师学习 Java — 免费
在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。
- 课程
- 21
- 课程
- 84
常见问题解答
「Spring WebFlux 与 Reactor Core」课时是免费的吗?
是的 — 「Spring WebFlux 与 Reactor Core」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Spring Boot 4 Complete Guide 课程的其余内容,请升级到 CoddyKit PRO。 Spring Boot 4 Complete Guide 课程共包含 4 节课。
「Spring WebFlux 与 Reactor Core」这节课中我会学到什么?
使用 Spring WebFlux 构建响应式 REST API,并操作 Reactor Core 中的 `Mono` 和 `Flux`。 你通过在浏览器中直接运行的动手代码来练习 Spring Boot 4 Complete Guide,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Spring Boot 4 Complete Guide 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Spring Boot 4 Complete Guide 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。
「Spring WebFlux 与 Reactor Core」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Spring Boot 4 Complete Guide 课中编写并运行代码吗?
能。每节 Spring Boot 4 Complete Guide 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 响应式编程简介
- Spring WebFlux 与 Reactor Core
- 响应式数据访问与集成
- 响应式流中的背压与错误处理