Skip to main content Link Menu Expand (external link) Document Search Copy Copied

일반적으로 Future와 WebFlux 를 비동기 구현에 사용하게 됩니다.

  • Future은 별도의 스레드를 호출하여 로직 실행 후, CallBack을 통해 리턴값을 전달받을 수 있죠.
  • WebFlux는 Flux/Mono 라는 이벤트 스트림을 만들고, 해당 스트림에 Pub/Sub하는 방식이죠. Flux/Mono는 어떻게 보면 이벤트 채널 이라고 볼 수 있겠죠? Flux와 함께 Sinks 객체를 사용하게 된다면 여러 스레드가 이 채널에 메세지를 전송할 수 있구요. 여러 스레드가 메세지를 받아볼 수도 있습니다.

1. CompletableFuture vs WebFlux

1-1. Via 컨셉

  • CompletableFuture is async and can be non-blocking
  • CompletableFuture is eager. You can’t postpone the execution. But you can cancel them (which is better than nothing)
  • WebFlux is async/non-blocking and can easily execute any call on different Thread by composing the main Mono with different operators.
  • WebFlux is truly lazy and allows postponing execution startup by the subscriber presence and its readiness to consume data.

To enable WebFlux support in Spring Security 5, we only need to specify the @EnableWebFluxSecurity annotation:

@EnableWebFluxSecurity
public class SecurityConfig {
    // ...
}

1-2. Via 컨트롤러 메소드 리턴타입

When the CompletableFuture is returned , it triggers Servlet 3.0 asynchronous processing feature which the execution of the CompletableFuture will be executed in other thread such that the server thread that handle the HTTP request can be free up as quickly as possible to process other HTTP requests. (See a series of blogpost start from this for detailed idea)

The @ResponseBody annotated on the @RestController will cause Spring to convert the controller method ‘s retuned value (i.e Person) through a HttpMessageConverter registered internally. One of its implementation is MappingJackson2HttpMessageConverter which will further delegate to the Jackson to serialise the Person object to a JSON string and send it back to the HTTP client by writing it to HttpServletResponse

Reference:https://stackoverflow.com/questions/54866391/mono-vs-completablefuture