Spring

[Spring] RestTemplate

박졔삐 2024. 10. 14. 20:52

[ RestTemplate ]

 

RestTemplate은 스프링 프레임워크에서 RESTful 웹 서비스와 통신하기 위한 동기식 HTTP 클라이언트이다.
REST API를 호출하고, JSON과 XML과 같은 다양한 형식의 데이터를 처리할 수 있도록 설계되었다.

 


1. 기본 개념

 

- REST : Representational State Transfer의 약자로, HTTP 프로토콜을 기반으로 하는 아키텍처 스타일. 
RESTful 서비스는 자원(리소스)에 대한 CRUD(Create, Read, Update, Delete) 작업을 HTTP 메서드(GET, POST, PUT, DELETE 등)를 통해 수행한다.
- RestTemplate: 스프링의 RestTemplate 클래스를 사용하여 RESTful 웹 서비스를 호출할 수 있다. 이는 스프링 3.0에서 처음 도입되었다.

 


2. 주요 메서드


RestTemplate은 다양한 HTTP 메서드에 대응하는 메서드를 제공한다. 주요 메서드는 다음과 같다 :


- GET : 리소스 조회.

ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);


- POST : 새로운 리소스 생성.

ResponseEntity<MyObject> response = restTemplate.postForEntity(url, requestBody, MyObject.class);


- PUT : 기존 리소스 업데이트.

restTemplate.put(url, requestBody);


- DELETE : 리소스 삭제.

restTemplate.delete(url);


- HEAD : 리소스의 헤더 정보 조회.

HttpHeaders headers = restTemplate.headForHeaders(url);




3. 설정

 

RestTemplate은 주로 다음과 같이 설정한다.

- 빈 등록 : 스프링 애플리케이션의 구성 파일에서 RestTemplate을 빈으로 등록할 수 있다.

@Bean
public RestTemplate restTemplate() {
    return new RestTemplate();
}



- 커스터 마이징 : RestTemplate은 다양한 클라이언트 설정을 커스터마이즈할 수 있다.

 

  1) 인터셉터 : 요청/응답을 가로채어 추가 작업을 수행할 수 있는 인터셉터를 추가할 수 있다.
  2) 메시지 변환기 : JSON, XML 등의 데이터 포맷을 처리하는 메시지 변환기를 추가할 수 있다.

 

 


4. 예외 처리

 

RestTemplate을 사용할 때 발생할 수 있는 예외를 처리할 수 있다. 주요 예외는 다음과 같다 :

- RestClientException : RESTful 호출 중 발생하는 일반적인 예외.
- HttpClientErrorException : 클라이언트 오류(4xx)가 발생했을 때 발생하는 예외.
- HttpServerErrorException : 서버 오류(5xx)가 발생했을 때 발생하는 예외.

 


예외 처리를 위한 방법: 

try {
    ResponseEntity<MyObject> response = restTemplate.getForEntity(url, MyObject.class);
} catch (HttpClientErrorException e) {
    // 클라이언트 오류 처리
} catch (HttpServerErrorException e) {
    // 서버 오류 처리
} catch (RestClientException e) {
    // 일반적인 REST 오류 처리
}



5. 사용 예제

 

다음은 RestTemplate을 사용하여 REST API를 호출하는 예제이다.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class MyService {

    private final RestTemplate restTemplate;

    @Autowired
    public MyService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public MyObject getData(String url) {
        ResponseEntity<MyObject> response = restTemplate.getForEntity(url, MyObject.class);
        return response.getBody();
    }

    public MyObject createData(String url, MyObject myObject) {
        ResponseEntity<MyObject> response = restTemplate.postForEntity(url, myObject, MyObject.class);
        return response.getBody();
    }

    public void updateData(String url, MyObject myObject) {
        restTemplate.put(url, myObject);
    }

    public void deleteData(String url) {
        restTemplate.delete(url);
    }
}




6. 추가 구성 요소

 

- HttpHeaders : 요청 및 응답의 헤더를 설정할 수 있다. 예를 들어, 인증 정보나 콘텐츠 타입을 지정할 수 있다.

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);



- UriComponentsBuilder : 동적 URL 생성을 위해 사용할 수 있다. URL에 쿼리 파라미터를 추가하는 데 유용하다.

String url = UriComponentsBuilder.fromUriString("http://example.com/api")
                                .queryParam("param", "value")
                                .toUriString();



7. 대안

 

스프링 5부터는 WebClient라는 비동기 HTTP 클라이언트가 추가되었다. 
RestTemplate은 여전히 많이 사용되지만, 새로운 프로젝트에서는 WebClient를 사용하는 것을 고려할 수 있다.
WebClient는 비동기 및 반응형 프로그래밍을 지원한다.



8. 결론


RestTemplate은 RESTful 웹 서비스를 호출하는데 유용한 도구. 다양한 HTTP 메서드와 예외 처리를 지원하고,
메시지 변환기와 인터셉터를 통해 커스터마이징 할 수 있다. 이를 통해 REST API와 통신을 간편하게 구현할 수 있다.

728x90
반응형