简体   繁体   中英

Connection Timeout in request with RestTemplate is not working correctly

I am using RestTemplate to get data from an external service, and I would like to set timeout for the request as follow:

        CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(RequestConfig.custom().setConnectTimeout(600000).setConnectionRequestTimeout(600000).setSocketTimeout(600000).build()).build();

        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
        requestFactory.setHttpClient(client);
        requestFactory.setConnectTimeout(600000);
        requestFactory.setConnectionRequestTimeout(600000);
        requestFactory.setReadTimeout(600000);

        RestTemplate restTemplate = new RestTemplate(requestFactory);

        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "Basic " + settings.getBase64EncodedAuthString());
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<BaseParameters> request = new HttpEntity<>(parameters, headers);

        ResponseEntity<MyResponse> response = restTemplate.exchange("https://my-external-service.com/service1", HttpMethod.POST,
                    request, MyResponse.class);

Although I have set the timeout to 600000ms (10 minutes), sometime I still got the timeout exception from server after only 20s, and this is the exception that I got:

org.springframework.web.client.ResourceAccessException -> I/O error on POST request for " https://my-external-service.com/service1 ": Connect to my-external-service.com:443 failed: Connection timed out: connect; nested exception is org.apache.http.conn.HttpHostConnectException: Connect to my-external-service.com:443 failed: Connection timed out: connect

Does anyone have an idea whether I made here something wrong with the timeout configuration or do I need to configure something more? Thank you

You are using HTTP request configuration, Request level configuration applies only once the connection route has been fully established. It does not apply to SSL handshakes or CONNECT requests. You need to configure socket properties applied by the connection manager upon connection creation.

This link will be helpful https://github.com/spring-projects/spring-boot/issues/11379

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM