Spring 숙련 (RestClient)

KimGwangmin·2026년 9월 14일

RestClient

HTTP 요청을 보내는 Spring 도구

서버가 클라이언트의 입장에서 다른 서버로 요청을 보낼 때 사용

예제

다음 의존성이 필요하다.

implementation 'org.springframework.boot:spring-boot-starter-restclient

GET 요청 보내기

@Slf4j
@Service
public class ExchangeRateClient {
    private final RestClient restClient;

    public ExchangeRateClient(
            RestClient.Builder builder,
            @Value("${rates.base-url}") String baseUrl
    ) {
        this.restClient = builder.baseUrl(baseUrl).build();
    }

    public ExchangeRateResponse fetch(
            String code
    ) {
        log.info("환율 API 호출: {}", code);
        return restClient.get() // 요청 메서드 종류
                .uri("/rates/{code}.json", code) // 요청 주소
                .retrieve() // 실제 요청을 날림(응답을 받아옴)
                .body(ExchangeRateResponse.class); // 응답 처리(DTO 매핑)
    }
}

예외 처리

  • 타임아웃 설정
# 연결 대기 최대 2초
spring.http.clients.connect-timeout=2s
# 연결 후 응답 대기 최대 2초
spring.http.clients.read-timeout=2s
  • 재시도(실패시 재호출)
    • @EnableResilientMethods 필요
    • 메서드에 @Retryable을 붙여 재시도 설정
@Configuration
@EnableResilientMethods
public class ResilienceConfig {
}
@Slf4j
@Service
public class ExchangeRateClient {
    private final RestClient restClient;

    public ExchangeRateClient(
            RestClient.Builder builder,
            @Value("${rates.base-url}") String baseUrl
    ) {
        this.restClient = builder.baseUrl(baseUrl).build();
    }

    @Retryable(
            includes = {HttpServerErrorException.class, ResourceAccessException.class}, // 재시도를 할 에러 상황 설정
            maxRetries = 2, // 최대 재시도 횟수
            delay = 200) // 재시도 간격
    public ExchangeRateResponse fetch(String code) {
        log.info("환율 API 호출: {}", code);
        return restClient.get()
                .uri("/rates/{code}.json", code)
                .retrieve()
                .body(ExchangeRateResponse.class);
    }
}

0개의 댓글