Spring RestClient
public class Foo implements Serializable {
private long id;
private String name;
// standard getters and setters
}
// Request Factory
ClientHttpRequestFactory requestFactory = getClientHttpRequestFactory();
RestTemplate restTemplate = new RestTemplate(requestFactory);
private ClientHttpRequestFactory getClientHttpRequestFactory() {
int timeout = 5000;
HttpComponentsClientHttpRequestFactory clientHttpRequestFactory
= new HttpComponentsClientHttpRequestFactory();
clientHttpRequestFactory.setConnectTimeout(timeout);
return clientHttpRequestFactory;
}
// GET Method
Foo foo = restTemplate
.getForObject(fooResourceUrl + "/1", Foo.class);
// POST Method
HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar"));
Foo foo = restTemplate.postForObject(fooResourceUrl, request, Foo.class);
RequestFactory With HttpClient
private ClientHttpRequestFactory getClientHttpRequestFactory() {
int timeout = 5000;
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(timeout)
.setConnectionRequestTimeout(timeout)
.setSocketTimeout(timeout)
.build();
CloseableHttpClient client = HttpClientBuilder
.create()
.setDefaultRequestConfig(config)
.build();
return new HttpComponentsClientHttpRequestFactory(client);
}
그외의 것들
- RestTemplate 객체는 무거운 객체이다. 한번 생성한 객체를 다시 사용하자
- 기본적으로 RestTemplate를 connection pool를 관리를 하지 않는다. 요청할때마다 connection을 만드는 구조이기 때문에 tcp connection이 증가가 할수 있다
- connection pool 도입하는 방법을 HttpClient를 이용하여 Reqeust Factory를 생성을 하면 된다.
HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
httpRequestFactory.setConnectTimeout(xxx);
httpRequestFactory.setReadTimeout(xxx);
HttpClient httpClient = HttpClientBuilder.create()
.setMaxConnTotal(xxx)
.setMaxConnPerRoute(xxx)
.build();
httpRequestFactory.setHttpClient(httpClient);
RestTemplate restTemplate = new RestTemplate(httpRequestFactory);
Reference
- http://www.baeldung.com/rest-template
'Programing > Java' 카테고리의 다른 글
Apache HttpClient Example (0) | 2018.07.29 |
---|---|
Java Object 비교 == (0) | 2018.07.25 |
Spock Framework을 이용한 Unit test 작성 (0) | 2018.06.25 |
Java Stream을 이용한 Inner Join / Left Join 기능 (0) | 2018.06.18 |
Lombok 상위클래스 필드를 이용한 객체 생성 방법 (0) | 2017.08.06 |