Trouble Shooting

[ERROR] Exceeded limit on max bytes to buffer 오류

야뤼송 2024. 7. 30. 08:07
반응형
WebClient로 API를 호출할 때 아래와 같은 에러가 발생
"org.springframework.core.io.buffer.DataBufferLimitException: Exceeded limit on max bytes to buffer : xxxxxx"

 

 

1. 발생원인 및 해결 방법

1) 발생원인 

WebClient 응답 시 기본 버퍼 사이즈인 256K를 초과하여 발생한 에러이다.

 

2) 해결책

WebClient codec의 maxInMemorySize에 값을 설정해주면 된다.

값 설정 시에는 본문 크기에 약간의 여유를 두는 것이 좋으며 만약 4MB의 응답이라면 약5~6MB정도로 설정하여 응답 처리 중에 추가적인 메모리 사용을 고려해주는 것이 좋다.

WebClient webClient = WebClient.builder()
                .codecs(configurer -> configurer
                    .defaultCodecs()
                    .maxInMemorySize(6 * 1024 * 1024)) // 메모리 크기를 6MB로 설정합니다.
                .build();

 

제한 없이 설정하기 위해서는 -1로 설정하면 되지만 너무 큰 값을 설정하게 되면 서버 메모리 부족, timeout등의 문제가 발생할 수 있다.

 

 

3) 응답 본문의 크기 측정

maxInMemorySize 값을 설정하기 위해 본문 응답의 크기를 측정하기 위해서는 doOnNext()를 이용하면 그 값을 측정할 수 있다.

 webClient.get()
    .uri(uri)
    .retrieve()
    .bodyToMono(String.class)
    .doOnNext(response -> {
        // 응답 본문 크기를 측정합니다.
        System.out.println("Response size: " + response.length() + " bytes");
    })
    .doOnError(error -> {
        System.err.println("error >> uri: " + uri + ", " + error.getMessage());
    })
    .subscribeOn(Schedulers.boundedElastic())
    .subscribe(response -> {
        // 응답을 처리합니다.
        System.out.println(response);
    });

 

반응형