การประมวลผลแบบอะซิงโครนัสด้วย WebFlux
ใช้การเขียนโปรแกรมเชิงรีแอ็กทีฟด้วย Spring WebFlux เพื่อสร้าง API ที่รองรับการทำงานพร้อมกันสูงและขยายระบบได้
การประมวลผลแบบอะซิงโครนัสด้วย WebFlux เป็นบทเรียน Spring Boot 4 Microservices & REST APIs ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 9 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Spring Boot 4 Microservices & REST APIs และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Spring Boot 4 Microservices & REST APIs มีบทเรียนทั้งหมด 9 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Why Reactive? The Blocking Problem
In traditional applications, when your code needs to wait for something (like a database query or an external API call), it often blocks the current thread.
This means the thread can't do anything else until the operation completes. For many concurrent users, this can lead to:
- High resource consumption (many threads).
- Slower response times under heavy load.
- Limited scalability.
Introducing Spring WebFlux
Spring WebFlux is Spring's reactive web framework, built on Project Reactor. It allows you to build asynchronous, non-blocking applications.
Unlike Spring MVC, which uses a thread-per-request model, WebFlux uses an event-loop model. This means a few threads can handle many concurrent requests efficiently, making your API more scalable.
Core Concepts: Mono and Flux
At the heart of reactive programming in Spring WebFlux are two publishers from Project Reactor:
- Mono: Represents a stream that emits 0 or 1 item, then completes (or errors). Think of it like an optional future value.
- Flux: Represents a stream that emits 0 to N items, then completes (or errors). This is for collections or continuous streams of data.
They don't do anything until someone subscribes to them!
Your First Reactive Endpoint
Let's create a basic WebFlux controller. Notice we return a Mono<String> instead of a plain String. This tells Spring WebFlux to handle the response reactively.
Try running this example and access /hello in your browser.
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
@SpringBootApplication
@RestController
public class WebfluxApp {
public static void main(String[] args) {
SpringApplication.run(WebfluxApp.class, args);
}
@GetMapping("/hello")
public Mono<String> hello() {
return Mono.just("Hello, WebFlux!");
}
}Transforming Data with 'map'
Mono and Flux provide operators to transform data. The map() operator applies a synchronous function to each emitted item.
Here, we transform the "hello" string to uppercase. The original data is not changed, a new transformed value is emitted.
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
@SpringBootApplication
@RestController
public class WebfluxApp {
public static void main(String[] args) {
SpringApplication.run(WebfluxApp.class, args);
}
@GetMapping("/greet")
public Mono<String> greet() {
return Mono.just("hello")
.map(String::toUpperCase)
.map(s -> s + " WORLD!");
}
}Working with Collections using Flux
When you need to return a stream of multiple items, Flux is your go-to publisher. It can emit zero, one, or many items over time.
Here's an example returning a Flux<String> of fruits. When accessed, the browser will receive the items as a JSON array or a stream, depending on the client's Accept header.
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
@SpringBootApplication
@RestController
public class WebfluxApp {
public static void main(String[] args) {
SpringApplication.run(WebfluxApp.class, args);
}
@GetMapping("/fruits")
public Flux<String> getFruits() {
return Flux.just("Apple", "Banana", "Cherry", "Date");
}
}Practical Example: Reactive User Service
Let's combine what we've learned. Imagine a simple User data class. We can create a service that returns a Flux<User>, simulating fetching users from a database with a slight delay to demonstrate asynchronicity.
This endpoint will stream users as they become available, rather than waiting for all of them.
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.time.Duration;
@SpringBootApplication
@RestController
public class WebfluxApp {
public static void main(String[] args) {
SpringApplication.run(WebfluxApp.class, args);
}
record User(String id, String name) {}
@GetMapping("/users")
public Flux<User> getUsers() {
return Flux.just(
new User("1", "Alice"),
new User("2", "Bob"),
new User("3", "Charlie")
)
.delayElements(Duration.ofMillis(500)); // Simulate async delay
}
@GetMapping("/users/{id}")
public Mono<User> getUserById(String id) {
return Mono.just(new User(id, "User " + id))
.delayElement(Duration.ofSeconds(1));
}
}Graceful Error Handling
Reactive streams can fail. WebFlux provides operators like onErrorResume() or onErrorReturn() to handle errors gracefully, allowing you to provide a fallback value or another reactive sequence.
Without error handling, a failed stream would propagate the error to the subscriber, potentially causing an application crash or an undesirable HTTP 500 status.
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
@SpringBootApplication
@RestController
public class WebfluxApp {
public static void main(String[] args) {
SpringApplication.run(WebfluxApp.class, args);
}
@GetMapping("/fail")
public Mono<String> failingEndpoint() {
return Mono.error(new RuntimeException("Something went wrong!"))
.onErrorResume(e -> {
System.err.println("Error: " + e.getMessage());
return Mono.just("Fallback Message");
});
}
}Why WebFlux Boosts Scalability
By adopting WebFlux, your applications can achieve higher throughput and better resource utilization, especially for I/O-bound tasks. This is because:
- Fewer Threads: A small number of threads can manage a large number of concurrent connections.
- Non-Blocking: Threads are not idly waiting; they handle other requests while I/O operations complete.
- Efficient Resource Use: Leads to lower memory footprint and CPU usage under high load.
This makes WebFlux ideal for microservices that frequently interact with external systems.
Quick Check on Reactive Types
Consider the core reactive types we just learned.
Recap: Embracing Reactive with WebFlux
Great job! You've taken your first steps into asynchronous programming with Spring WebFlux.
- We learned how blocking I/O limits scalability.
- Spring WebFlux provides a non-blocking, reactive alternative.
- Mono handles 0-1 items, and Flux handles 0-N items.
- These publishers enable more efficient resource usage and higher concurrency.
Next, explore how to integrate WebFlux with reactive data repositories for end-to-end non-blocking applications!
คำถามที่พบบ่อย
บทเรียน “การประมวลผลแบบอะซิงโครนัสด้วย WebFlux” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การประมวลผลแบบอะซิงโครนัสด้วย WebFlux” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Spring Boot 4 Microservices & REST APIs ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Spring Boot 4 Microservices & REST APIs มีบทเรียนทั้งหมด 9 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การประมวลผลแบบอะซิงโครนัสด้วย WebFlux”
ใช้การเขียนโปรแกรมเชิงรีแอ็กทีฟด้วย Spring WebFlux เพื่อสร้าง API ที่รองรับการทำงานพร้อมกันสูงและขยายระบบได้ คุณปฏิบัติ Spring Boot 4 Microservices & REST APIs ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Spring Boot 4 Microservices & REST APIs หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน Spring Boot 4 Microservices & REST APIs บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 9 บทเรียน
บทเรียน “การประมวลผลแบบอะซิงโครนัสด้วย WebFlux” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน Spring Boot 4 Microservices & REST APIs นี้ได้ไหม
ได้ บทเรียน Spring Boot 4 Microservices & REST APIs ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การเพิ่มประสิทธิภาพอัตราการส่งข้อความ
- การประมวลผลแบบอะซิงโครนัสด้วย WebFlux
- การปรับปรุงโครงสร้างข้อมูล
- การขยายคอนซูเมอร์และโปรดิวเซอร์
- กลยุทธ์แคชสำหรับไมโครเซอร์วิส
- แนวทางการทำให้ข้อมูลไม่เป็นรูปแบบปกติ
- การแบ่งส่วนและการทำสำเนาฐานข้อมูล
- การติดตามและแก้จุดบกพร่องฐานข้อมูล
- การวัดประสิทธิภาพ RabbitMQ