WebSockets & Real-Time Systems with Spring · บทเรียน

การสร้างบริการเรียลไทม์เชิงรีแอกทีฟ

พัฒนาบริการเรียลไทม์เชิงรีแอกทีฟตั้งแต่ต้นจนจบ โดยใช้ประโยชน์จาก Project Reactor

บทเรียน 3 จาก 411 ขั้นตอน

การสร้างบริการเรียลไทม์เชิงรีแอกทีฟ เป็นบทเรียน WebSockets & Real-Time Systems with Spring ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน WebSockets & Real-Time Systems with Spring และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส WebSockets & Real-Time Systems with Spring มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Reactive Real-Time Services

Welcome! In this lesson, we'll build end-to-end reactive real-time services using Spring WebFlux and Project Reactor.

Reactive services are excellent for handling many concurrent connections efficiently. They offer better scalability and responsiveness compared to traditional blocking approaches.

Project Reactor: Flux & Mono

At the heart of reactive programming in Spring is Project Reactor. It provides two key types for handling data streams:

  • Flux: Represents a stream of 0 to N items. Think of it as a publisher that can emit multiple values over time.
  • Mono: Represents a stream of 0 to 1 item. Useful for operations that return a single result or no result (like void).

These types allow us to compose asynchronous operations in a clear and non-blocking way.

WebFlux WebSocket Handlers

Spring WebFlux uses the WebSocketHandler interface to manage WebSocket connections. Its main method, handle(), takes a WebSocketSession and returns a Mono.

This Mono signifies that the handling process is complete once the reactive stream it represents finishes. We can use Flux inside to send continuous messages.

Designing a Reactive Data Source

To build a real-time service, we need a source of data. Let's create a simple Flux that emits a message periodically. This simulates a real-time data feed, like a stock ticker or a sensor reading.

We'll use Flux.interval() to generate events and map() to transform them into useful messages.

Implementing a Ticker Service

Here's a basic WebSocketHandler that sends a 'tick' message every second. It uses the Flux.interval() we discussed.

The session.send() method takes a Flux to push data to the client.

import org.springframework.web.reactive.socket.WebSocketHandler;
import org.springframework.web.reactive.socket.WebSocketMessage;
import org.springframework.web.reactive.socket.WebSocketSession;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.Duration;

public class TimeTickerHandler implements WebSocketHandler {

    @Override
    public Mono<Void> handle(WebSocketSession session) {
        // Send messages to the client
        Flux<WebSocketMessage> output = Flux.interval(Duration.ofSeconds(1))
            .map(i -> session.textMessage("Tick #" + i));

        // Receive messages from the client (and ignore them for now)
        // We use .then() to ensure the Mono<Void> completes only when the session closes.
        Mono<Void> input = session.receive().then();

        return session.send(output).and(input);
    }
}

Full Runnable Ticker Service

To make our TimeTickerHandler runnable, we need a Spring Boot application. This example sets up the WebFlux server and registers our handler.

Access this via ws://localhost:8080/ticker in a WebSocket client (like Postman or a browser's DevTools console) to see it in action.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping;
import org.springframework.web.reactive.socket.WebSocketHandler;
import org.springframework.web.reactive.socket.WebSocketMessage;
import org.springframework.web.reactive.socket.WebSocketSession;
import org.springframework.web.reactive.socket.server.support.WebSocketHandlerAdapter;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@SpringBootApplication
public class ReactiveTickerApplication {

    public static void main(String[] args) {
        SpringApplication.run(ReactiveTickerApplication.class, args);
    }

    @Bean
    public SimpleUrlHandlerMapping webSocketHandlerMapping(WebSocketHandler webSocketHandler) {
        Map<String, WebSocketHandler> map = new HashMap<>();
        map.put("/ticker", webSocketHandler);
        return new SimpleUrlHandlerMapping(map, 1);
    }

    @Bean
    public WebSocketHandler webSocketHandler() {
        return new WebSocketHandler() {
            @Override
            public Mono<Void> handle(WebSocketSession session) {
                // Send a 'tick' message every second
                Flux<WebSocketMessage> output = Flux.interval(Duration.ofSeconds(1))
                    .map(i -> session.textMessage("Tick #" + i + " at " + System.currentTimeMillis()));

                // Handle incoming messages (e.g., echo them back, or process commands)
                // For this example, we'll just log and then complete the input stream
                Mono<Void> input = session.receive()
                    .doOnNext(msg -> System.out.println("Received: " + msg.getPayloadAsText()))
                    .then(); // ensures the Mono completes after processing all incoming

                return session.send(output).and(input);
            }
        };
    }

    @Bean
    public WebSocketHandlerAdapter handlerAdapter() {
        return new WebSocketHandlerAdapter();
    }
}

Handling Client Input

Our previous ticker only sent data. To make it truly interactive, we can also process messages coming from the client.

The session.receive() method returns a Flux that represents incoming messages. You can subscribe to this Flux to react to client input, for example, by filtering, transforming, or using the data to control the output stream.

Error Handling in Reactive Streams

Errors can occur in any part of a reactive pipeline. Project Reactor provides operators to handle these gracefully, preventing your application from crashing:

  • onErrorResume(): Recovers from an error by switching to an alternative publisher.
  • doOnError(): Performs a side-effect (like logging) when an error occurs, then re-throws it or completes.
  • retry(): Retries the sequence if an error occurs.

Using these helps build robust real-time services that can recover from transient issues.

Backpressure Management

Backpressure is crucial for reactive systems. It's a mechanism where a consumer can signal to a producer that it's receiving data too quickly and needs the producer to slow down.

Project Reactor handles backpressure automatically. When a client can't keep up, the WebSocket connection might buffer messages or eventually close, but the server-side Flux won't overwhelm itself or the network.

Reactive Service Concepts

Which of the following are key characteristics of building reactive real-time services with Spring WebFlux and Project Reactor?

Recap: Reactive Real-Time

We've explored how to build reactive real-time services using Spring WebFlux and Project Reactor.

  • We saw how Flux can generate continuous data streams.
  • We implemented a WebSocketHandler to push these streams to clients.
  • We configured a basic Spring Boot application to host our reactive WebSocket endpoint.
  • We touched upon error handling and backpressure, vital for robust systems.

These principles enable highly scalable and responsive real-time applications.

เริ่มต้นได้ฟรี

เรียนรู้ WebSockets & Real-Time Systems with Spring ด้วย AI tutor — ฟรี

เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป

คอร์ส
12
บทเรียน
48

คำถามที่พบบ่อย

บทเรียน “การสร้างบริการเรียลไทม์เชิงรีแอกทีฟ” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การสร้างบริการเรียลไทม์เชิงรีแอกทีฟ” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส WebSockets & Real-Time Systems with Spring ให้อัปเกรดเป็น CoddyKit PRO คอร์ส WebSockets & Real-Time Systems with Spring มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การสร้างบริการเรียลไทม์เชิงรีแอกทีฟ”

พัฒนาบริการเรียลไทม์เชิงรีแอกทีฟตั้งแต่ต้นจนจบ โดยใช้ประโยชน์จาก Project Reactor คุณปฏิบัติ WebSockets & Real-Time Systems with Spring ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน WebSockets & Real-Time Systems with Spring หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน WebSockets & Real-Time Systems with Spring บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน

บทเรียน “การสร้างบริการเรียลไทม์เชิงรีแอกทีฟ” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน WebSockets & Real-Time Systems with Spring นี้ได้ไหม

ได้ บทเรียน WebSockets & Real-Time Systems with Spring ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. บทนำสู่การเขียนโปรแกรมเชิงรีแอกทีฟ
  2. ตัวจัดการ WebFlux WebSocket
  3. การสร้างบริการเรียลไทม์เชิงรีแอกทีฟ
  4. การจัดการแรงดันย้อนกลับในสตรีมแบบรีแอกทีฟ
← กลับไปที่ WebSockets & Real-Time Systems with Spring