이전 포스팅에서 HTTP 통신 방식에 대해 다룬 포스팅이 있다.
자세한 내용은 아래 참고 포스팅에 참고 바란다.
오늘은 그 중 하나인 방법인 RestTemplate에 대해서 다뤄볼 것이다.
그리고 이 RestTemplate을 학습하기 위해서는 HttpClient 도 같이 알면 도움이 된다.
자세한 내용은 아래 참고 포스팅 참고 바란다.
RestTemplate (Spring Framework 6.1.6 API)
postForLocation Create a new resource by POSTing the given object to the URI template, and return the value of the Location header. This header typically indicates where the new resource is stored. URI Template variables are expanded using the given URI va
docs.spring.io
RestTemplate이란
- Spring 3.0 부터 지원 이 되고 복잡한 HttpClient 사용을 한번 추상화한 객체이다.
- HttpClient는 HTTP를 사용하여 통신하는 범용 라이브러리이고, RestTemplate은 HttpClient 를 추상화해서 제공한다.
- 또한 Restful 원칙을 지키며 단순 메소드 호출만으로 쉽게 HTTP 요청을 주고 받을 수 있도록 도와주는 HTTP 통신 템플릿이다.
(Restful에 대해서는 아래 참고 포스팅 참고)
- RestTemplate 은 기본적으로 connection pool 을 사용하지 않고 RestTemplate은 호출할 때마다, 로컬에서 임시 TCP 소켓을 개방하여 사용한다. 그러기에 이렇게 사용된 TCP 소켓은 TIME_WAIT 상태가 되는데, 요청량이 많아지면 TIME_WAIT 상태의 소켓들은 재사용 될 수 없기 때문에 응답에 지연이 생기기 마련이다. 이럴때를 대비해서 Connection Pool을 이용할 수 있다.
(단 Connection Pool 설정하려면 API 서버에 Keep-Alive를 지원이 되야함)
Connection pool 설정을 위해서는 다음과 같다.
우선 HttpComponentsClientHttpRequestFactory 를 사용해서 Connection Pool을 사용할 것이고
RestTemplateConfig 를 만들어서 Bean 등록을 하면 된다.
@Configuration public class RestTemplateConfig { @Bean HttpClient httpClient() { return HttpClientBuilder.create() .setMaxConnTotal(100) .setMaxConnPerRoute(30) .build(); } @Bean HttpComponentsClientHttpRequestFactory factory(HttpClient httpClient) { HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(); factory.setReadTimeout(5000); factory.setConnectTimeout(3000); factory.setHttpClient(httpClient); return factory; } @Bean RestTemplate restTemplate(HttpComponentsClientHttpRequestFactory factory) { return new RestTemplate(factory); } } |
그리고 실제 Http 요청은 아래와 같이 보낸다.
..이상 생략 ResponseEntity<String> response = restTemplate.exchange( "destination주소", HttpMethod.POST, //method 방식 entity, //input data String.class //return type ); ..이하 생략 |
RestTemplate 주요 메서드는 아래와 같다.
RestTemplate Method | HTTP Method | 설명 |
execute | Any | |
exchange | Any | 헤더세팅해서 HTTP Method로 요청보내고 ResponseEntity로 반환받음 |
getForObject | GET | get 요청을 보내고 java object로 매핑받아서 반환받음 |
getForEntity | GET | get 요청을 보내고 ResponseEntity로 반환받음 |
postForLocation | POST | post 요청을 보내고 java.net.URI 로 반환받음 |
postForObject | POST | post 요청을 보내고 ResponseEntity로 반환받음 |
put | PUT | |
delete | DELETE | |
headForHeaders | HEAD | |
optionsForAllow | OPTIONS |
참고 포스팅
https://thenicesj.tistory.com/817
Java 에서 Http 통신 방식 3가지(RestTemplate, WebClient, OpenFeign)
Spring Framework 는 다양하게 Http 요청 방식을 지원하고 통신을 제공한다. 3가지 방식에 대해서 간단히 작성해볼것이다. Http 통신 에 대한 내용은 아래 참고 포스팅을 참고 바란다. 1. RestTemplate RestTemp
thenicesj.tistory.com
https://thenicesj.tistory.com/919
Apache HttpClient 와 CloseableHttpClient 차이점 +(DefaultHttpClient / HttpClientBuilder)
우선 HttpClient 란 HTTP 메서드를 실행하는것이 주 목적이다.일반적으로는 HttpClient에 의해 내부적으로 처리된다. 여기서 만들어진것이 CloseableHttpClient 이다.CloseableHttpClient는 HttpClient의 기본 구현인
thenicesj.tistory.com
https://thenicesj.tistory.com/120
REST API / RESTful API 차이점?
REST(REpresentational State Transfer) 자원을 이름으로 구분해서 해당 자원의 상태를 주고 받는 것을 의미한다. 즉, resource(자원) 의 represeㅜtation(표현) 에 의한 상태 전달이다. HTTP 프로토콜을 그대로 사용
thenicesj.tistory.com
'IT > Java' 카테고리의 다른 글
NamedQuery 에 대해 (16) | 2024.05.07 |
---|---|
Spring Cloud에 대해 (16) | 2024.05.05 |
Apache HttpClient 와 CloseableHttpClient 차이점 +(DefaultHttpClient / HttpClientBuilder) (29) | 2024.05.01 |
줄바꿈 하기 (\n, \r, \r\n 의 차이) / System.lineSeparator() (31) | 2024.04.30 |
Workbook 사용법 (20) | 2024.04.28 |
댓글