반응형
spring에서 외부로 API 호출을 하기 위해 RestTemplate를 사용한다.
restTemplate 사용방법과 속성(Connect 타임아웃, 재시도, 리드타임아웃)을 설정하는 방법 정리
1. API 호출시
method | http | comment |
getForObject | GET | GET 방식으로 호출, 결과는 객체로 반환 |
getForEntity | GET | GET 방식으로 호출. 결과는 ResponseEntity로 반환 |
postForLocation | POST | POST방식으로 호출. 결과는 헤더에 저장된 URI로 반환 |
postForObject | POST | POST방식으로 호출. 결과는 객체로 반환 |
postForEntity | POST | POST방식으로 호출. 결과는 ResponseEntity로 반환 |
delete | DELETE | DELETE 방식으로 호출. |
headForHeaders | HEADER | 헤더의 모든 정보를 얻을 수 있으며, HTTP HEAD 매서드 사용 |
put | PUT | HTTP PUT 매서드 실행 |
patchForObject | PATCH | HTTP PATCH 매서드 실행 |
optionsForAllow | OPTIONS | 지원하는 HTTP 매서드 조회 |
exchange | ANY | HTTP 헤더 생성 및 어떤 HTTP 매서드(get, post, put 등)도 사용가능. |
execute | ANY | request/response 콜백을 수정할 수 있다. |
2. 사용방법(exchange 사용)
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", access_token);
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
headers.setContentType(MediaType.APPLICATION_JSON);
JSONObject json = new JSONObject();
json.put("test", "restTemplate");
HttpEntity<String> request = new HttpEntity<String>(json.toString(), headers);
// POST 방식 호출
ResponseEntity<String> postMap = restTemplate.exchange("https://api_url.com/test/abc", HttpMethod.POST, request, String.class);
// GET 방식 호출
ResponseEntity<String> getMap = restTemplate.exchange("https://api_url.com/test/abc?apiKey=123&test=ok", HttpMethod.GET, new HttpEntity<>(headers), String.class);
LOGGER.info("resultMap.getStatusCodeValue() = " + postMap.getStatusCodeValue());
LOGGER.info("resultMap.getBody() = " + getMap.getBody());
3. 속성 적용
- connect time out :
.setConnectTimeout(Duration.ofSeconds(3))
- read time out
.setReadTimeout(Duration.ofSeconds(3))
- retry
. dependencies 추가
implementation 'org.springframework.retry:spring-retry'
implementation 'org.springframework:spring-aspects'
. 코드
.additionalInterceptors(clientHttpRequestInterceptor())
- 속정 적용 코드
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.retry.policy.SimpleRetryPolicy;
import org.springframework.retry.support.RetryTemplate;
import org.springframework.web.client.RestTemplate;
import java.time.Duration;
@Configuration
public class Config {
@Bean
public RestTemplate restTemplate() {
return new RestTemplateBuilder()
.setConnectTimeout(Duration.ofSeconds(3))
.setReadTimeout(Duration.ofSeconds(3))
.additionalInterceptors(clientHttpRequestInterceptor())
.build();
}
public ClientHttpRequestInterceptor clientHttpRequestInterceptor() {
return (request, body, execution) -> {
RetryTemplate retryTemplate = new RetryTemplate();
retryTemplate.setRetryPolicy(new SimpleRetryPolicy(2));
try {
return retryTemplate.execute(context -> execution.execute(request, body));
} catch (Throwable throwable) {
throw new RuntimeException(throwable);
}
};
}
}
끝
반응형
'Java' 카테고리의 다른 글
window SDKMAN 설치 (0) | 2023.06.14 |
---|---|
spring boot properties 여러개(분기) 동적으로 사용하는 방법 (0) | 2022.05.31 |
로컬에 있는 jar파일 추가하는 방법(gradle) (0) | 2022.05.31 |
Mapper로 SQL 호출하기 (0) | 2022.04.08 |
no main manifest attribute in 오류 발생 (0) | 2022.04.08 |