신비한 개발사전
RestTemplate vs RestClient 본문
RestTemplate와 RestClient는 HTTP 요청을 보낼 수 있는 HttpClient다. HttpClient를 활용하면 서버 입장에서도 다른 서버에 HTTP 요청을 전송할 수 있다.
RestTemplate and RestClient share the same infrastructure (i.e. request factories, request interceptors and initializers, message converters, etc.), so any improvements made therein are shared as well. However, RestClient is the focus for new higher-level features.
과거 해프닝으로 인해 RestTemplate가 deprecated됐다는 얘기가 돌았지만, RestTemplate도 계속해서 지원되고 있다. 다만 RestClient가 최신 API 스펙에 맞는 더 많은 기능을 수행할 수 있고, Spring도 RestClient 사용을 권장하고 있다. RestClient는 Spring 6.1에 추가되었다.
RestTemplate
RestTemplate은 getForEntity, getForObject 등의 메서드를 사용해 호출한 API의 응답 본문을 자바 객체로 매핑해 받아올 수 있는 인터페이스를 제공한다.
public List<Todo> getTodos() {
try {
ResponseEntity<Todo[]> response = restTemplate.getForEntity("http://jsonplaceholder.typicode.com/todos/", Todo[].class);
if (response.getBody() == null) return List.of();
return Arrays.asList(response.getBody());
} catch (HttpClientErrorException e) {
// ...
}
return List.of();
}
RestClient
RestClient는 내부적으로 RestTemplate을 활용하는, 더욱 사용자 친화적인 API다. RestTemplate에 비해 더욱 직관적인 메서드 네이밍과 메서드 체이닝을 사용하는 것이 특징이다.
public List<Todo> getTodos() {
Todo[] todoBody = restClient.get()
.uri("/todos")
.retrieve()
.body(Todo[].class);
return Arrays.asList(todoBody);
}
개인적으로는 메서드 체이닝을 통해 선언형으로 코드를 작성할 수 있는 RestClient를 더 선호한다. 가독성 측면에서 RestClient의 방식이 코드를 더 빠르게 파악할 수 있는 편이라고 생각한다.
또한 RestClient가 더 최신 스펙과 개발 트렌드를 변영한 거라, 기술의 발전이 나날이 빨라지는 시대임을 고려했을 때 장기적으로는 RestClient 사용이 유지보수에 더 수월할 것이라고 판단된다.
'Backend' 카테고리의 다른 글
@Embedded, @Embeddable로 객체지향적인 JPA 엔티티 설계하기 (0) | 2025.05.25 |
---|---|
@Transactional 유무에 의한 로직 동작 차이 (0) | 2025.05.22 |
@DataJpaTest 롤백은 id까지 초기화해주지 않는다 (0) | 2025.05.17 |
Spring MVC 동작에 대한 전체적인 복습 (0) | 2025.05.14 |
@Sql로 테스트 데이터 사용 시 유의할 점 (0) | 2025.05.10 |