Programing/Java

Spring RestTemplate

BUST 2018. 7. 22. 15:14

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