本文详细介绍了Spring RestTemplate中关于超时设置的方法,包括HttpURLConnection的ConnectTimeout和ReadTimeout属性,以及如何通过Command Line Args、SimpleClientHttpRequestFactory和HttpComponentsClientHttpRequestFactory进行配置。特别推荐使用HttpComponentsClientHttpRequestFactory并自定义HttpClient来设置超时和连接池。
Spring org.springframework.web.client.RestTemplate 使用 org.springframework.http.client.SimpleClientHttpRequestFactory建立 java.net.HttpURLConnection
后者采用 HttpURLConnection 的默认超时配置
HttpURLConnection 超时属性
ConnectTimeout(ms)
a specified timeout value, in milliseconds, to be used when opening a communications link to the resource referenced by this URLConnection.
If the timeout expires before the connection can be established, a java.net.SocketTimeoutException is raised. A timeout of zero is interpreted as an infinite timeout.
ReadTimeout(ms)
a specified timeout, in milliseconds.
A non-zero value specifies the timeout when reading from Input stream when a connection is established to a resource.
If the timeout expires before there is data available for read, a java.net.SocketTimeoutException is raised.
A timeout of zero is interpreted as an infinite timeout