본문 바로가기
Computer/Server

summary of async, webflux

by 생각하는달팽이 2022. 8. 4.

sevlet 3.0 버전 이하의 async call과 servlet 3.1 의 webflux는 어떤 차이가 있는지 살펴보자.

 

우선 Webflux 의 경우 공식문서에서 다음처럼 얘기한다

Spring MVC relies on Servlet blocking I/O and lets applications use the Servlet API directly if they need to. Spring WebFlux relies on Servlet 3.1 non-blocking I/O and uses the Servlet API behind a low-level adapter

직역하자면 Webflux 는 Servlet 3.1 의 non-blocking I/O 에 의존한다고 되어있다.

 

그렇다면 서두에서 얘기한  Servlet 3.0 이하의 api의 blocking I/O 라는 어떤 의미일까? 다음 내용을 살펴보자.

In a typical application, ServletInputStream is read in a while loop. However, if the incoming data is blocked or is streamed slower, the server thread must wait for the data. The same situation can happen if the data is written to 
ServletOutputStream

데이터를 받는 부분에서 blocking 이 생기거나, streaming 이 느려지면 서버 쓰레드는 반드시 기다려야한다는 의미이다.

다시 말해, servlet async 에서 futuer 와 같은 async 한 작업을 진행할 때. 보통 이경우 thread pool 을 만들어 재사용을 하는데 thread count 만큼의 요청을 동시처리 할 수 있다. 다만, 문제는 I/O 작업이 일어나는 상황에서 thread 가 blocking 이 되는데, 이 경우에 thread 들이 모두 가득 차있다면, 추가 요청들에 대해 timeout 이 떨어질 수 있다.

 

그렇다면, Servlet 3.1 non-blocking I/O 는 어떤식으로 구현이 됐길래, blocking 이 안생길까..?

Servlet 3.1 resolves the problem by adding event listeners: ReadListener and WriteListener interfaces. You register these event listeners by using ServletInputStream.setReadListener and ServletOutputStream.setWriteListener
. The listeners have callback methods that are invoked when the content is available to be read or that can be written without blocking.

요약하면 Listener 에는 callback method 가 존재하는데, 해당 callback method는 contents를 읽을 수 있을 때 호출돼고, blocking 없이 쓸 수 있도록 고안되었다. 

이렇게 되면, 기존 servlet 에서 발생하던 thread blocking 없이 처리를 하게되면서, 상대적으로 대량의 요청 처리를 진행할 수 있게 된다. 

 

다만 위의 설명들은 tomcat, jetty 기반으로 동작할 경우이고. netty 를 사용할 경우 servlet 을 쓰지 않는다.

Spring WebFlux is supported on Tomcat, Jetty, Servlet 3.1+ containers, as well as on non-Servlet runtimes such as Netty and Undertow. All servers are adapted to a low-level, common API so that higher-level programming models
 can be supported across servers.

 

_ 왜 꼭 webflux 를 써야하는지 고민을 하는데 도움이 될까 글을 정리해본다.

 

 

참고 링크

https://docs.spring.io/spring-framework/docs/current/reference/html/web-reactive.html#webflux-server-choice
https://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HTML5andServlet31/HTML5andServlet%203.1.html#overview

 

반응형