Spring Boot设置RestTemplate的超时时间

参考:http://stackoverflow.com/questions/13837012/spring-resttemplate-timeout

Java Config方式

@Configuration
public class RestTemplateConfig {

    @Bean
    //@LoadBalanced   //增加 load balance 特性
    public RestTemplate restTemplate() {
        ClientHttpRequestFactory factory = simpleClientHttpRequestFactory();
        return new RestTemplate(factory);
    }

    public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setReadTimeout(15000);  //单位为ms
        factory.setConnectTimeout(15000);  //单位为ms
        return factory;
    }

}

或者

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

        return new RestTemplate(httpRequestFactory);
    }
}

配置文件指定

rest-template:
  connection:
    connection-request-timeout: 5000
    connect-timeout: 5000
    read-timeout: 5000
@Configuration
public class RestTemplateConfig {
    @Bean
    @ConfigurationProperties(prefix = "rest-template.connection")
    public HttpComponentsClientHttpRequestFactory customHttpRequestFactory() {
        return new HttpComponentsClientHttpRequestFactory();
    }

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

版权声明:
作者:Joe.Ye
链接:https://www.appblog.cn/index.php/2023/03/19/spring-boot-sets-timeout-time-for-resttemplate/
来源:APP全栈技术分享
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
打赏
海报
Spring Boot设置RestTemplate的超时时间
参考:http://stackoverflow.com/questions/13837012/spring-resttemplate-timeout Java Config方式 @Configuration public class RestTemplateConfig { ……
<<上一篇
下一篇>>
文章目录
关闭
目 录