Spring WebClient Blocking 응답 문제

dropKick·2024년 4월 17일

개발 이슈

목록 보기
8/14

개요

✅ Spring WebFlux는 기본적으로 비동기 & 논블로킹 방식으로 동작
✅ blocking으로 결과를 받으려 한 경우 예외 발생

  • WebFlux 내부에서는 블로킹이 이루어질 수 없음

WebFlux에서 블로킹을 받으려는 경우

Mono<String> response = webClient.get()
    .uri("https://example.com/api")
    .retrieve()
    .bodyToMono(String.class);

String result = response.block(); // Exception
System.out.println(result);
  • block() 호출 시 현재 WebFlux 스트림을 잡고있는 Netty 스레드는 응답이 올 때까지 블럭
  • 이 경우 스레드 자체가 멈추고, 비동기 - 블로킹 방식이 되어 비동기의 의미가 없어짐

그러면 블로킹으로 응답을 못받나요?

블로킹 응답 형태

Mono<String> response = webClient.get()
    .uri("https://example.com/api")
    .retrieve()
    .bodyToMono(String.class);

String result = response.subscribeOn(Schedulers.boundedElastic()).block();
System.out.println(result);

블로킹 스트림 형태

Mono<String> response = webClient.get()
    .uri("https://example.com/api")
    .retrieve()
    .bodyToMono(String.class)
    .publishOn(Schedulers.boundedElastic())
    .doOnNext(res -> System.out.println("Response: " + res));

response.subscribe();
  • 별도 스레드를 생성하는 방식으로 블로킹 구현이 가능하지만 추천 X
  • 블로킹 연산이 필요하다면 애초에 분리하는게 맞음
profile
안아줘요

0개의 댓글