개요
Spring WebFlux 는 SpringMVC 와 유사한 annotated Controller 형식으로 웹 애플리케이션을 위한 반응형, 비동기, 비차단 프로그래밍 지원을 제공합니다.
이러한 접근 방식은 Node.js가 비동기, 논블로킹 모델을 사용하여 확장성을 높이는 방식과 유사합니다. Spring WebFlux 는 유사한 모델을 사용하지만 여러 이벤트 루프를 사용합니다.
Spring WebFlux는 기존 Spring MVC 의 요청당 스레드 차단 모델에서 벗어나 멀티 이벤트 루프, 비동기, Non blocking 패러다임으로 이동하여 기존 blocking 보다 뛰어난 확장성과 효율성을 제공합니다.
Spring Reactive Stack
Spring Reactive Stack 은 아래 5가지로 구성되어있습니다.
- Spring Boot 2+
- Project Reactor
- Spring WebFlux
- Netty
- Spring Data Reactive Repositories
Why Use Spring WebFlux?
Spring WebFlux 를 사용하면 CPU 및 네트워크 리소스를 보다 효율적으로 활용하고 확인 가능한 아키텍처와 더욱 빠른 사용자 경험을 제공할 수 있습니다.
Why was Spring WebFlux created?
Part of the answer is the need for a non-blocking web stack to handle concurrency with a small number of threads and scale with fewer hardware resources.
…
That is important because of servers such as Netty that are well-established in the async, non-blocking space.
…
The other part of the answer is functional programming.
The addition of lambda expressions in Java 8 created opportunities for functional APIs in Java. This is a boon for non-blocking applications and continuation-style APIs that allow declarative composition of asynchronous logic.
Spring WebFlux Framework
Spring WebFlux 는 반응형 스트림 사양을 구현하는 Project Reactor 를 기반으로 합니다.
Reactive Streams is an initiative to provide a standard for asynchronous stream processing with non-blocking back pressure.
This encompasses efforts aimed at runtime environments (JVM and JavaScript) as well as network protocols.
WebFlux 는 아래 두가지 패러다임을 제공합니다.
- Annotation-based Spring Controllers
- Functional Endpoints that allow for functional, fluent API style routing and handler functions
Annotated Spring WebFlux RestController
@RestController
@RequestMapping("api/v1/room/reservation/")
public class ReservationResource {
@GetMapping(path = "/{roomId}")
public Mono<Reservation> getReservationById(@PathVariable Mono<String> roomId) {
return //Call your service layer here
}
}
보시다시피 이 코드는 반환 유형이 Reactive Controller(이 경우에는 예약 객체(이 샘플 프로젝트의 DTO)를 반환하는 Mono)라는 점을 제외하면 Spring MVC와 매우 유사합니다.
Mono: a Reactive Publisher that emits 1 or zero elements than terminates.
다시 말해, Mono는 요소를 리턴하는 비동기, 프로미스 또는 Future와 같습니다.
- Flux 와 Mono 는 Reactive Stream Specification 을 구현한 reactive type 임
- Flux 와 Mono 는 reactor-core 모듈의 일부임
- Flux 는 0~N 원소의 reactive type을 표현함
- Mono 는 0 과 1 element 의 reactive type 을 표현함
Flux - 0 to N elements
https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Flux.html
Mono - 0 to 1 Element
https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Mono.html
'프레임워크 > Spring' 카테고리의 다른 글
[Spring] - 개요 (1) | 2024.02.15 |
---|