java - Spring RestTemplate 不会使用超时设置

标签 java spring spring-boot resttemplate hystrix

无法理解 RestTemplate 如何处理超时。

我将 RestTemplate 配置为 Bean,如下所示:

@Bean
public RestTemplate rest(final RestTemplateBuilder builder) {
    final RestTemplate restTemplate = new RestTemplate(getClientHttpRequestFactory());
    return restTemplate;
}

private ClientHttpRequestFactory getClientHttpRequestFactory() {
    final int timeout = 50000;
    final RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).setSocketTimeout(timeout).build();
    final CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
    return new HttpComponentsClientHttpRequestFactory(client);
}

50000的值只是一个学术值。

我在 Hystrix 包装的服务连接器中使用我的 RestTemplate:

@HystrixCommand(commandProperties = { @HystrixProperty(name = "execution.isolation.strategy", value = "SEMAPHORE") }, fallbackMethod = "fallbackActivityCall")
public Optional<ResponseActivityValue> callForActivity() {
    final StringBuilder urlBuilder = new StringBuilder(accessConfig.getTracking().getUrl());
    final HttpEntity<String> entity = new HttpEntity<>(buildAuthHeader());

    final ResponseEntity<ResponseActivityValue> re = restTemplate.exchange(urlBuilder.toString(), HttpMethod.GET, entity, ResponseActivityValue.class);
    final HttpStatus code = re.getStatusCode();
    return Optional.ofNullable(re.getBody());
}

我用停止调用的服务对其进行了测试。该方法在 3 秒后返回,而不是预期值 50000。无论我在 RestTemplate 中配置哪个值,它总是在 3 秒后返回。

有人有想法吗?

最佳答案

可以直接使用RestTemplateBuilder构建器来构建您的休息模板实例:如下

@Bean
public RestTemplate rest(final RestTemplateBuilder builder) {
    return builder
             .setConnectTimeout(50000)
             .setReadTimeout(50000)
             .build()
}

并尝试在 application.properties 中设置 hysterix 的配置

hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=50000

或者直接在命令中(@HystrixProperty)

@HystrixCommand(
  commandProperties = { 
    @HystrixProperty(name = "execution.isolation.strategy", value = "SEMAPHORE"), 
    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "50000")  
}, fallbackMethod = "fallbackActivityCall")
public Optional<ResponseActivityValue> callForActivity() {
 ....
} 

关于java - Spring RestTemplate 不会使用超时设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54125573/

相关文章:

java外部while循环不迭代

java - 除了log4j xml、属性文件和源代码(主要是java)之外,还有其他方式配置日志吗?

spring-boot - 如何生成包含一些自定义声明的 JWT 访问 token ?

Spring Boot 移除 Whitelabel 错误页面

java - org.apache.catalina.LifecycleException : Failed to start component [StandardEngine[Catalina]. StandardHost[本地主机].StandardContext[/mmasgis]]

java - 无法运行docker镜像

java - 我需要一个正则表达式来分割 CSV 文件中的数千个内容

java - 设置形状颜色的不透明度

java - 引号内定义的字符数组?

java - 如何将 Spring Config XML 迁移到 Spring Boot 注释