Netty에서부터 Spring WebFlux의 요청 처리 흐름을 알아보겠습니다.

1. 클라이언트 요청 수신 - Netty 서버

WebFlux는 기본적으로 Reactor Netty(Netty 위에 Reactor 프로그래밍 모델을 입힌 HTTP/TCP 클라이언트 & 서버 구현체)를 HTTP 서버로 사용합니다. Netty는 Java NIO 기반의 비동기 이벤트 기반 네트워크 프레임워크입니다.

1-1. Netty의 부트스트랩 과정

Spring Boot를 통해 WebFlux 애플리케이션이 시작되면:

protected void onRefresh() {
      super.onRefresh();

      try {
          this.createWebServer();
      } catch (Throwable ex) {
          throw new ApplicationContextException("Unable to start reactive web server", ex);
      }
  }

스프링 애플리케이션 컨텍스트 초기화 완료를 위해 super.onRefresh( ) 가 실행된 후 this.createWebServer( ) 로 Netty 웹 서버 생성 및 실행합니다.

this.createWebServer( ) 의 내부에서 아래 실행 로직이 실행됩니다:

HttpServer.create()
          .port(8080)
          .handle(new ReactorHttpHandlerAdapter(webHandler))
          .bindNow();

<aside> 💡

HttpHandler와 WebHandler는 무엇인가요?

배경

Spring WebFlux는 다음과 같이 다양한 서버 엔진과 함께 사용할 수 있습니다:

각 서버는 자체적인 HTTP 처리 방식과 API를 가지고 있습니다. 예를 들어 Netty는 ChannelHandler , Servelet 기반 서버는 HttpServlet 방식으로 HTTP 요청을 처리합니다.

HttpHandler란?

HttpHandler 는 WebFlux에서 HTTP 요청과 응답을 처리하는 가장 핵심적인 추상화 인터페이스입니다.

public interface HttpHandler {
    Mono<Void> handle(ServerHttpRequest request, ServerHttpResponse response);
}

이 인터페이스는 다음에 활용됩니다:

WebHandler란?

Spring WebFlux에서의 WebHandler는 다음과 같은 인터페이스입니다:

public interface WebHandler {
    Mono<Void> handle(ServerWebExchange exchange);
}

즉, HTTP 요청을 처리하는 핵심 WebFlux 컴포넌트입니다.

좀 더 쉽게 말하면:

HttpHandler가 서버 추상화라면,

WebHandlerWebFlux 애플리케이션 로직을 처리하는 실질적인 핸들러입니다.

항목 HttpHandler WebHandler
위치 서버 엔진과 요청 처리의 경계 WebFlux 내부 요청 처리의 중심
인풋 ServerHttpRequest, ServerHttpResponse ServerWebExchange
목적 서버 독립성 보장, 추상화된 입출력 라우팅, 필터 처리, 핸들러 호출 등 수행
구현체 예시 ReactorHttpHandlerAdapter DispatcherHandler, RouterFunctions
</aside>

<aside> 💡

ReactorHttpHandlerAdapter 생성자 파라미터 타입은 HttpHandler인데 어떻게 WebHandler 인터페이스 구현체인 DispatcherHandler가 들어갈 수 있나요?

Spring WebFluxDispatcherHandlerHttpHandler 로 감싸서 넘깁니다. 보통 다음과 같은 빌더를 사용합니다.

WebHandler webHandler = new DispatcherHandler();

HttpHandler httpHandler = WebHttpHandlerBuilder
                            .webHandler(webHandler)
                            .build();

ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(httpHandler);

즉, DispatcherHandlerWebHandler 지만, WebHttpHandlerBuilder.build( ) 는 이걸 내부에서 HttpHandler 로 감싸는 작업을 합니다.

</aside>

2. Netty에서 요청 수신

클라이언트가 HTTP 요청을 보내면: