반응형


RestTemplate 설정 예제


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
    HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
    // 읽기타임아웃 - 5초동안 연결은 되었지만 처리 속도가 느려 응답 없으면 타임아웃
    factory.setReadTimeout(5000); // milliseconds
    // 연결타임아웃 - 5초동안 연결이 되지 않으면 타임아웃(잘못된 주소 연결 혹은 서비스 다운)
    factory.setConnectTimeout(5000);// milliseconds
 
    // 커넥션 풀 설정
    HttpClient httpClient = HttpClientBuilder.create()//
        .setMaxConnTotal(50)// IP:PORT 관계없이 전체 커넥션 수
        .setMaxConnPerRoute(50)// IP:PORT 마다 커넥션 수
        .build();
    factory.setHttpClient(httpClient);
    // 커넥션 풀 설정
 
    RestTemplate restTemplate = new RestTemplate(factory);
 
    HttpClientContext context = HttpClientContext.create();
    restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory() {
      @Override
      protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) {
        if (context.getAttribute(HttpClientContext.COOKIE_STORE) == null) {
          context.setAttribute(HttpClientContext.COOKIE_STORE, new BasicCookieStore());
          Builder builder = RequestConfig.custom()
              // .setCookieSpec(CookieSpecs.IGNORE_COOKIES)
              // .setAuthenticationEnabled(false)
              .setRedirectsEnabled(false);
          context.setRequestConfig(builder.build());
        }
        return context;
      }
    });



http client

1
2
3
4
    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
    </dependency>


import

1
2
3
4
5
6
7
8
9
10
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.config.RequestConfig.Builder;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.HttpContext;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;


반응형

+ Recent posts