RestClient
。Spring Application이 다른서버의API를 호출하기 위한Http Client 객체
。Spring 서버가 주로AI 서버/결제 서버등의마이크로 서비스에HTTP 요청전송 시 사용
RestClient 메서드
。.get()/.post()/.put()/.delete()/.patch()가 존재.
Spring Bean으로 등록@Configuration public class RestClientConfig { @Bean public RestClient restClient() { return RestClient.create(); } }
GET 요청UserResponse response = restClient.get() .uri("http://localhost:8081/users/1") .retrieve() .body(UserResponse.class);。
get():GET 요청
。uri(URI):URI 주소
。retrieve().body(객체): 해당객체로 변환하여 응답을 받는 경우 정의
Query ParameterList<UserResponse> users = restClient.get().uri (uriBuilder -> uriBuilder .path("/users") .queryParam("page", 1) .queryParam("size", 20) .build()) .retrieve() .body(new ParameterizedTypeReference<>() {});
POST 요청UserResponse response = restClient.post() .uri("http://localhost:8081/users") .body(request) .retrieve() .body(UserResponse.class);
JWT를 같이 요청하는 경우UserResponse response = restClient.get() .uri("http://localhost:8081/users") .header("Authorization", "Bearer " + token) .retrieve() .body(UserResponse.class);
Generic적용private <T, V> V requestToAi( String endpoint, T data, Class<V> respType ){ return restClient.post() .uri(aiBaseUrl + endpoint) .body(data) .retrieve() .body(respType); }