스프링 부트

[SpringBoot] RestTemplate 구성하기!

h__hj 2022. 11. 27. 16:07

# RestTemplate  - @Configuration

 스프링 부트에서 사용하는 RestTemplate 설정 예제 코드 입니다.

# 환경

Tool  : STS 4.13.0
Ver   : 2.7.5 [GA]
JDK   : 11
Repo  : MAVEN
DB    : ORACLE XE (11g)
View  : Thymeleaf
jQuery: 3.6.0

# Configuration

@Configuration
public class RestTemplateConfig {
    
    private final int TIMEOUT = 10 * 1000;
    private final int MAX_CONN_TOTAL_VALUE = 30;
    private final int MAX_CONN_PER_ROUTE_VALUE = 5;
    
    @Bean(name = "template")
    public RestTemplate template() {
        
        // https://www.baeldung.com/rest-template
        /**
         * 요청에 대한 기본적인 설정.
         * ConnectTimeout: 연결이 설정될 때까지 시간 초과(밀리초)를 결정합니다. 
         * ConnectionRequestTimeout: 연결 관리자에게 연결을 요청할 때 사용되는 시간 초과(밀리초)를 반환합니다. 
         * SocketTimeout: 소켓 시간 초과(밀리초)를 정의합니다. 즉, 데이터를 대기하기 위한 시간 제한입니다. 다르게 표현하자면, 두 개의 연속된 데이터 패킷 사이의 최대 비활동 기간).
         * 
         * 제한 시간 값이 0이면 무한 제한 시간으로 해석됩니다. 음수 값은 정의되지 않은 것으로 해석됩니다(해당하는 경우 시스템 기본값). 기본 값: {@code -1}
         */
        RequestConfig requestConfig = RequestConfig.custom()
                                                  .setConnectTimeout(TIMEOUT)
                                                  .setConnectionRequestTimeout(TIMEOUT)
                                                  .setSocketTimeout(TIMEOUT)
                                                  .build();
        /**
         * 추가 구성 옵션을 위해 HttpClient를 사용
         * MaxConnTotal: 최대 총 연결 값을 할당합니다.
         * MaxConnPerRoute: 경로 값당 최대 연결 수를 할당합니다.
         */
        CloseableHttpClient httpClient = HttpClientBuilder.create()
                                                    .setDefaultRequestConfig(requestConfig)
                                                    .setMaxConnTotal(MAX_CONN_PER_ROUTE_VALUE)
                                                    .setMaxConnPerRoute(MAX_CONN_PER_ROUTE_VALUE)
                                                    .build();
        
        return this.setRestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient));
    }
    
    private RestTemplate setRestTemplate(HttpComponentsClientHttpRequestFactory factory) {
        
        // BufferingClientHttpRequestFactory
        // 메모리의 모든 송수신 스트림을 버퍼링하는 ClientHttpRequestFactory의 래퍼입니다. 이 래퍼를 사용하면 응답 본문을 여러 번 읽을 수 있습니다.
        RestTemplate template = new RestTemplate(new BufferingClientHttpRequestFactory(factory));
        
        // REST TEMPLATE SET INTERCEPTOR
        template.setInterceptors(Collections.singletonList(new RestTemplateInterceptor()));
        
        // REST TEMPLATE SET ERROR HANDLER
        template.setErrorHandler(new RestTemplateInterceptor());
        
        // REST TEMPLATE MESSAGE CONVERTERS
//        List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
//        converters.add(new MappingJackson2HttpMessageConverter());
//        converters.add(new FormHttpMessageConverter());
        
//        template.setMessageConverters(converters);
        
        return template;
    }

# 내용

설정은 어렵지 않다!

# RestTemplate 시리즈

https://hjho95.tistory.com/35 getForObject, postForObject
https://hjho95.tistory.com/36 exchange (POST, PUT, DELETE)
https://hjho95.tistory.com/37 Configuration 
https://hjho95.tistory.com/38 ClientHttpRequestInterceptor, ResponseErrorHandler 

# RestTemplate 시리즈 참조 페이지

RestTemplate: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html
RestTemplate: https://www.baeldung.com/rest-template
Interceptor: https://www.baeldung.com/spring-rest-template-interceptor
ErrorHandling: https://www.baeldung.com/spring-rest-template-error-handling