0Pricing
Spring Boot 4 Complete Guide · 강의

Spring WebFlux 및 Reactor Core

Reactor Core의 `Mono`와 `Flux`를 활용해 Spring WebFlux로 리액티브 REST API를 구축합니다.

Spring WebFlux 및 Reactor Core은(는) CoddyKit의 무료 Spring Boot 4 Complete Guide 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 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.

자주 묻는 질문

“Spring WebFlux 및 Reactor Core” 강의는 무료인가요?

네 — “Spring WebFlux 및 Reactor Core” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Spring Boot 4 Complete Guide 강의 전체를 잠금 해제할 수 있습니다. Spring Boot 4 Complete Guide 강의에는 총 4개의 강의가 포함되어 있습니다.

“Spring WebFlux 및 Reactor Core”에서 뭘 배우나요?

Reactor Core의 `Mono`와 `Flux`를 활용해 Spring WebFlux로 리액티브 REST API를 구축합니다. 브라우저에서 직접 실행하는 실습 코드로 Spring Boot 4 Complete Guide을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Spring Boot 4 Complete Guide을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Spring Boot 4 Complete Guide은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“Spring WebFlux 및 Reactor Core” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Spring Boot 4 Complete Guide 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Spring Boot 4 Complete Guide 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 리액티브 프로그래밍 입문
  2. Spring WebFlux 및 Reactor Core
  3. 리액티브 데이터 접근 및 통합
  4. 리액티브 스트림의 백프레셔와 오류 처리
← Spring Boot 4 Complete Guide(으)로 돌아가기