Spring rest template readTimeOut

こ雲淡風輕ζ 提交于 2019-12-08 19:15:49

问题


I'm trying to understand the readTimeout available on restTemplate, what is it exactly ?

Is it the the total amount of time the request can take before we get the timeout exception ?


回答1:


You can define a read timeout on a RestTemplate as follows:

HttpComponentsClientHttpRequestFactory clientRequestFactory = new HttpComponentsClientHttpRequestFactory();
// set the read timeot, this value is in miliseconds
clientRequestFactory.setReadTimeout(500);

RestTemplate restTemplate = new RestTemplate(clientRequestFactory);

Given a readTimeout of X millis, any request made through that RestTemplate instance which takes longer than X millis will result in a ResourceAccessException, wrapping a java.net.SocketTimeoutException with the exception message: "Read timed out".

The timeout is actually implemented by the socket connector inside the HttpClient instance which is wrapped by the RestTemplate so the clock starts when the request first hits that socket and stops when whichever of these comes first: the request completes or the readTimeout is reached.

In effect this means that any request which takes longer than the configured readTmeout will fail with a timeout exception.




回答2:


As far as i knew, In restTemplate we have 3 type of timeouts

  1. ConnectionRequestTimeout. This is timeout in millis for getting connection from connectionManager

  2. ConnectionTimeout. This is timeout in millis for establishing connection between source and destination

  3. ReadTimeout. This is timeout in millis which expects the response/result should be returned from the destination endpoint.




回答3:


You can also define a bean:

@Bean
public RestTemplate restTemplateReadTimeout(RestTemplateBuilder builder) {
    return builder
            .setReadTimeout(15000) //15 seconds
            .build();
}

And use it:

@Autowired
@Qualifier("restTemplateReadTimeout")
private RestTemplate restTemplate;

PS.: When I used this configuration on Spring Boot, I tried to create different RestTemplate Beans with different timeout configurations. But I ended up seeing Spring using always only one timeout configuration (probably using the timeout from the last bean registered), acting as the timeout configuration was a Singleton among the RestTemplates. So pay attention on that, I don't know if was some mistake on my configuration, bug or expected behavior.



来源:https://stackoverflow.com/questions/45713767/spring-rest-template-readtimeout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!