본문 바로가기

WebClient10

WebClient + Retry + CircuitBreaker WebClient 를 이용할 때, Retry 기능과 CircuitBreaker 기능을 추가할 수 있다. 구체적인 방법과 함께 테스트 코드는 어떻게 만드는지 알아보자. 먼저 전체 코드를 간단히 훑어보고 뒤에서 자세히 설명하겠다. 응답 status code 가 501 이상이면, CircuitBreakerException 을 만들어서 넘긴다. 하지만 timeout 에러면 0.5초 간격으로 1번 retry 를 수행한다. retry 를 수행해도 에러가 발생하면 RetryExhaustedException 으로 감싸져서 나오기 때문에 onErrorMap 으로 잡아서 cause 를 빼내 뒤로 전달한다. .exchangeToMono(clientResponse -> { if (clientResponse.rawStatusC.. 2022. 9. 24.
WebClient 사용할때 주의 (8편) 1. WebClient config 기본 구조 설명 WebClient 를 사용하기 위해선 WebClientBuilder 를 활용해 만드는데 clientConnector 인자로 ReactorClientHttpConnector 객체를 생성해 넣어준다. return webClientBuilder.baseUrl(apiClientProperties.getUrl()) .clientConnector( // ReactorClientHttpConnector 를 넣어줘야함 ) .build(); cf) ReactorClientHttpConnector 객체를 생성하기 위해선 reactorResourceFactory 가 필요한데, 따로 빈 등록해야한다. 물론 없어도 객체 생성이 가능하지만 내가 만든 코드에서는 필요했다. @Be.. 2022. 9. 18.
WebClient 사용할때 주의 (7편) webClient 사용할 때 주의사항까진 아니지만 리스트 형태의 response body 를 받는 방법에 대해서 간단히 정리했다. 가끔 Mono 형태로 리턴 webClient 코드를 볼 때가 있다. flatMapIterable 메서드로 Flux 를 사용하는게 좋다. public Flux getData() { return this.webClient.get() .uri(uriBuilder -> uriBuilder .path("/data") .build() ) .retrieve() .bodyToMono(DataApiResponse.class) .flatMapIterable(DataApiResponse::getContent); } @Value public class DataApiResponse { List co.. 2022. 3. 7.
WebClient 사용할때 주의 (6편) WebClient 로 요청을 보내고 받은 응답 객체는 아래와 같다. 이때 message 값이 nullable 하다고 해보자. public class ResponseDto { private String id; @Nullable private String message; public String getMessage() { return message; } } ResponseDto 로 deserialize 한 후에 map 연산자를 이용해 message 를 가져오면 NPE가 발생한다. webClientBuilder ... 생략 .retrieve() .bodyToMono(ResponseDto.class) .map(responseDto -> responseDto.getMessage()) .onErrorResume(t.. 2021. 12. 15.
WebClient 사용할때 주의 (5편) Metric 먼저 Webclient 레벨에서 보내는 metric과 내부 구현체인 reactor.netty 레벨에서 보내는 metric 은 서로 다르다. WebClient 레벨에서 보내는 metric은 DefaultWebClientExchangeTagsProvider 에서 설정해서 보내고 있으며, uri template 단위로 태그 하고 있다. public class DefaultWebClientExchangeTagsProvider implements WebClientExchangeTagsProvider { @Override public Iterable tags(ClientRequest request, ClientResponse response, Throwable throwable) { Tag method.. 2021. 11. 11.
WebClient 사용할때 주의 (4편) 이전 WebClient 글 예제 코드로 아래와 같이 clientResponse.createException().flatMap() 과 onErrorResume 을 사용했는데 flatMap 을 해서 다시 Mono.error 로 감싸는, 어떻게 보면 비효율적인 코드다. AS-IS .retrieve() .onStatus( httpStatus -> httpStatus != HttpStatus.OK, clientResponse -> { return clientResponse.createException() .flatMap(it -> Mono.error(new RuntimeException("code : " + clientResponse.statusCode()))); }) .bodyToMono(String.class.. 2021. 11. 5.