Springboot RestTemplate设置超时时间

Java Config方式

Spring boot 版本<=1.3

@Configuration
public class AppConfig{
    @Bean
    public RestTemplate customRestTemplate(){
        HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
        httpRequestFactory.setConnectionRequestTimeout(3000);
        httpRequestFactory.setConnectTimeout(3000);
        httpRequestFactory.setReadTimeout(3000);

        return new RestTemplate(httpRequestFactory);
    }
}

配置文件方式指定

custom.rest.connection.connection-request-timeout=3000
custom.rest.connection.connect-timeout=3000
custom.rest.connection.read-timeout=3000
@Configuration
public class AppConfig{
    @Bean
    @ConfigurationProperties(prefix = "custom.rest.connection")
    public HttpComponentsClientHttpRequestFactory customHttpRequestFactory() {
        return new HttpComponentsClientHttpRequestFactory();
    }

    @Bean
    public RestTemplate customRestTemplate(){
        return new RestTemplate(customHttpRequestFactory());
    }
}

Spring boot 版本>=1.4

@Configuration
public class AppConfig
{
    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) 
    {
        return restTemplateBuilder
           .setConnectTimeout(...)
           .setReadTimeout(...)
           .build();
    }
}

你可能感兴趣的:(Spring,Springboot,rest,restTemplate,Spring,restTemplate)