0Pricing
Spring Boot 4 Microservices & REST APIs · 강의

WebFlux를 사용한 비동기 처리

Spring WebFlux로 반응형 프로그래밍을 구현하여 높은 동시성과 확장성을 갖춘 API를 만듭니다.

WebFlux를 사용한 비동기 처리은(는) CoddyKit의 무료 Spring Boot 4 Microservices & REST APIs 강의입니다. 이것은 9개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 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를 사용한 비동기 처리” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Spring Boot 4 Microservices & REST APIs 강의 전체를 잠금 해제할 수 있습니다. Spring Boot 4 Microservices & REST APIs 강의에는 총 9개의 강의가 포함되어 있습니다.

“WebFlux를 사용한 비동기 처리”에서 뭘 배우나요?

Spring WebFlux로 반응형 프로그래밍을 구현하여 높은 동시성과 확장성을 갖춘 API를 만듭니다. 브라우저에서 직접 실행하는 실습 코드로 Spring Boot 4 Microservices & REST APIs을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Spring Boot 4 Microservices & REST APIs을(를) 시작하는 데 경험이 필요한가요?

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

“WebFlux를 사용한 비동기 처리” 강의는 얼마나 걸리나요?

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

이 Spring Boot 4 Microservices & REST APIs 강의에서 코드를 작성하고 실행할 수 있나요?

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

이 강의의 모든 강의

  1. 메시지 처리량 최적화
  2. WebFlux를 사용한 비동기 처리
  3. 데이터 구조 최적화
  4. 소비자 및 생산자 확장
  5. 마이크로서비스 캐싱 전략
  6. 비정규화 전략
  7. 데이터베이스 샤딩 및 복제
  8. 데이터베이스 모니터링 및 디버깅
  9. RabbitMQ 성능 벤치마킹
← Spring Boot 4 Microservices & REST APIs(으)로 돌아가기