기존 Spring MVC로 충분하지 않을까?
그런데 왜 WebFlux가 나왔고, 뭘 위해 쓸까?
예를 들어
- 실시간 채팅, 알림, 대용량 이벤트/데이터 스트림 처리 등
- “많은 연결, 빠른 응답”이 필요한 서비스에 적합
구분 | Spring MVC | Spring WebFlux |
---|---|---|
실행 모델 | 동기, 블로킹 | 비동기, 논블로킹 |
Servlet 지원 | Tomcat/Jetty(서블릿 기반) | Netty, Undertow, 서블릿/비서블릿 모두 지원 |
리턴 타입 | ModelAndView , ResponseEntity | Mono , Flux (리액티브 타입) |
대표 Usecase | CRUD, 관리 UI 등 | 실시간 알림, API Gateway 등 |
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-webflux'
}
package com.example.demo.web;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;
import reactor.core.publisher.Flux;
@RestController
@RequestMapping("/api")
public class SampleController {
@GetMapping("/hello")
public Mono<String> hello() {
return Mono.just("Hello, WebFlux!");
}
@GetMapping("/numbers")
public Flux<Integer> numbers() {
return Flux.range(1, 10);
}
}
Mono
, Flux
타입 활용)실시간 알림/메시지/스트리밍 (예: 채팅, 주식 시세, IoT)
I/O Bound (네트워크/DB에 대기 많은 서비스)
대량 동시접속 처리가 필요할 때 (ex: API Gateway)
단,
Mono/Flux
변환에 익숙해져야 함 (처음엔 Stream/Optional 쓸 때와 비슷)block()
남발 x)