랄라

RestTemplate 본문

내일배움캠프/공부정리

RestTemplate

devdaeun 2025. 2. 11. 07:49

클라이언트로부터 받은 요청중에서 다른 서버에게서 정보를 받아오거나 요청을해야할때,

server to server로 정보를 간편하게 요청할수 있도록 만든 기능, 동기적 처리만을 지원한다

*네이버,카카오 API와 같은 외부 API에 요청할때 사용.

 

*동기적 처리

더보기

요청을 받았을경우 응답을 완료할때까지 해당 흐름을 블로킹(Blocking)하여 다른 요청이 접근하지못하도록하는 처리.

네트워크 지연이 발생할경우 성능에 영향을 줄 수 있다.


생성방법

1. 생성자 주입

private final RestTemplate restTemplate;

//RestTemplateBuilder 사용하여 RestTemplate 생성자 주입
public RestTemplateService(RestTemplateBuilder builder) {
        this.restTemplate = builder.build();
    }

RestTemplateBuilder

- RestTemplate의 기본 URL 설정, 타임아웃 설정등을 위한 메소드를 제공하는 클래스.

 

2. 빈으로 생성하여 주입

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class AppConfig {

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

*RestTemplate를 Bean으로 등록하였을경우 다른 클래스에서 사용시 상단에 @Autowired 표기! (손쉬운 사용가능)


getForEntity() / postForEntity()

   URI uri = UriComponentsBuilder
            .fromUriString("http://{url}") //기본 URL 주소
            .path("{mapping 경로}") 
            .queryParam("query", query) //쿼리값, 경로뒤에?로 시작하는 부분
            .encode() //공백등을 인코딩처리
            .build() //작성한 url을 빌드
            .toUri(); //빌드된 UriComponents를 URI 객체로 변환
ResponseEntity<타입> responseEntity = restTemplate.getForEntity(uri, [받아올 타입].class);
// GET 요청을 보내고 응답을 객체로 받음


ResponseEntity<타입> responseEntity = restTemplate.postForEntity(uri, user, [받아올 타입].class);
//POST 요청을 보내고 응답을 객체로 받음

//받아올 타입과 동일한 클래스 타입 사용

 

exchange()

Header에 정보를 추가하여 전달하고싶을때 사용.

ResponseEntity<String> response = restTemplate.exchange(url, 메소드 타입, 전달정보, [받아올 타입].class);

 

'내일배움캠프 > 공부정리' 카테고리의 다른 글

Docker 란?  (0) 2025.03.04
JPA Entity  (1) 2025.02.11
Spring Cloud  (1) 2025.02.07
MSA와 MA의 정의  (0) 2025.02.07
AWS 배포중 발생한 오류 해결 (80포트 접속 불가능)  (0) 2025.02.05