본문 바로가기
web/SpringBoot

[WebClient] Memory Leak

by 뽀리님 2023. 12. 15.

WebClient 를 쓸경우 메모리 누수가 생기는 경우가 더러있다.

그게 언제냐! 하믄

 

첫째, 헤더누적

둘째, 예외가 생겼는데 예외처리를 하지 않을 경우

셋째, exchange()

넷째, WebClient 낮은버전

 

✔  헤더 누적

미리 webClient 생성해놓고 필요할 때마다 재사용을  

this.webClient = WebClient.builder()
            .clientConnector(connector)
       		.baseUrl("http://google.com")
            	.header("test", "123") // 주의 !!
       		.build()
       		.post();

사용하고자 하는 쪽에서 아래와 같이 header 메서드를 쓴다면 reqest header 계속 누적되어 append 되는 문제가 발생한다.

아래와 같이 쓰자

.defaultHeader("test", "123")

 

 

 

예외가 발생했는데 처리하지 않을 경우

 Subscribe()

webClient.get()
        .uri("/api/resource")
         .retrieve()
         .bodyToMono(String.class)
         .subscribe(response -> {
        // 처리 로직
    }, error -> {
        // 에러 처리 로직 필수
        log.error("Error in WebClient request", error);
    });

 

 

✔ Exchange() 쓰지말자

exchange 메서드는 retrieve 보다 세밀한 컨트롤이 가능한 대신 memory leak 주의 해야 한다.

// 문제가 있는 코드
.exchange()
.flatMap(res -> res.toEntity(String.class))
            .doOnSuccess(
            result -> {
        if (result.getStatusCode() == HttpStatus.OK) {
            String body = result.getBody();
            doProcess(body);
        } else {
            // empty
        }
    });

응답 Body 를 소비(consume)

하지않으면 누수가 발생함

그냥 권고하는대로 retrieve() 쓰자.

 

✔ 낮은버전

낮은 버전을 쓰는경우 종종 생길수가있다. 최신버전을 이용토록 하자.

 

참조 :

https://gngsn.tistory.com/154