1. IDE
Intellij
2. 오늘 공부 내용
RestTemplate
- RestTemplate - 동기(Synchronous) 방식의 HTTP 클라이언트, RESTful 웹 서비스를 호출하기 위해 사용
RestTemplate 주요 기능
- HTTP 요청 전송 및 응답 수신: RestTemplate은 다양한 HTTP 메서드를 지원하여 서버로부터 데이터를 가져오거나, 데이터를 서버에 보낼 수 있습니다.
- GET: 데이터를 조회할 때 사용됩니다.
- POST: 서버에 데이터를 전송할 때 사용됩니다.
- PUT: 서버에 데이터를 업데이트할 때 사용됩니다.
- DELETE: 서버에서 데이터를 삭제할 때 사용됩니다.
- PATCH: 서버에서 데이터의 일부를 업데이트할 때 사용됩니다.
- URI 템플릿 지원: URI 템플릿을 사용하여 요청 시 URL의 동적 매핑을 지원합니다.
- 예:
https://api.example.com/users/{id}에서 {id} 부분을 실제 값으로 대체.
- 객체 직렬화 및 역직렬화: 요청 시 객체를 JSON이나 XML 형식으로 변환하고, 응답을 객체로 변환하는 기능을 제공합니다.
ObjectMapper와 같은 Jackson 라이브러리를 사용하여 JSON 변환을 수행합니다.
- 예외 처리: 응답 상태 코드에 따라
HttpClientErrorException, HttpServerErrorException과 같은 예외를 자동으로 던져줍니다.
RestTemplate 사용 방법
- RestTemplate 객체 생성
RestTemplate restTemplate = new RestTemplate();
- HTTP GET 요청
String url = "https://api.example.com/users/1";
User user = restTemplate.getForObject(url, User.class);
- getForObject() 메서드는 지정된 URL로 HTTP GET 요청을 보내고, 응답을 지정된 클래스 타입으로 변환하여 반환합니다.
- HTTP POST 요청
String url = "https://api.example.com/users";
User newUser = new User("John", "Doe");
User createdUser = restTemplate.postForObject(url, newUser, User.class);
- postForObject() 메서드는 지정된 URL로 HTTP POST 요청을 보내고, 요청 본문에 데이터를 포함하며, 응답을 지정된 클래스 타입으로 변환하여 반환합니다.
- HTTP PUT 요청
String url = "https://api.example.com/users/1";
User updatedUser = new User("John", "Doe");
restTemplate.put(url, updatedUser);
- put() 메서드는 지정된 URL로 HTTP PUT 요청을 보내고, 요청 본문에 데이터를 포함하지만 응답 본문은 반환하지 않습니다
- HTTP DELELTE 요청
String url = "https://api.example.com/users/1";
restTemplate.delete(url);
- URL 템플릿 사용
String url = "https://api.example.com/users/{id}";
Map<String, String> params = new HashMap<>();
params.put("id", "1");
User user = restTemplate.getForObject(url, User.class, params);
- getForObject() 메서드는 {id} 템플릿 변수를 params 맵에 있는 값으로 대체합니다.
- 요청 및 응답 헤더 설정
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("Authorization", "Bearer your_token_here");
HttpEntity<User> requestEntity = new HttpEntity<>(newUser, headers);
ResponseEntity<User> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, User.class);
- exchange() 메서드는 HTTP 메서드를 지정하고, 요청과 응답을 더 세밀하게 제어할 수 있게 해줍니다.
RestTemplate의 예외 처리
- HttpClientErrorException: 4xx 클라이언트 오류 발생 시.
- HttpServerErrorException: 5xx 서버 오류 발생 시.
- ResourceAccessException: 네트워크 오류 발생 시.
- RestClientException: 그 외 일반적인 RestTemplate 오류 발생 시.
try {
User user = restTemplate.getForObject(url, User.class);
} catch (HttpClientErrorException e) {
// 4xx 에러 처리
} catch (HttpServerErrorException e) {
// 5xx 에러 처리
} catch (RestClientException e) {
// 기타 예외 처리
}
RestTemplate의 한계와 대안
- Spring Boot 2.4부터 RestTemplate은 비동기 방식의 WebClient로 대체가 권장되고 있습니다.
- RestTemplate은 동기 방식이므로, 요청을 보내면 응답이 올 때까지 블로킹됩니다.
- WebClient는 비동기 및 논블로킹 방식으로, 높은 성능과 확장성을 제공합니다.
결론
- RestTemplate은 Spring에서 HTTP 요청을 간단하게 처리할 수 있는 유용한 도구입니다. 동기식 처리가 필요하고 복잡하지 않은 HTTP 클라이언트 기능을 구현할 때 적합합니다
- 동기 처리나 대규모 애플리케이션의 경우 WebClient를 사용하는 것이 권장