通过@ConfigurationProperties为HttpClientBuilder设置ConnectionKeepAliveStrategy

时间:2017-05-16 10:09:35

标签: java spring

我可以为HttpClientBuilder设置某些属性(例如maxConnTotal),如下所示:

YAML

http.client.max-conn-total: 10

的java

@Bean
@ConfigurationProperties(prefix = "http.client")
public HttpClientBuilder httpClientBuilder() {
  return HttpClientBuilder.create();
}

我希望还有一种设置ConnectionKeepAliveStrategy的方法,因为我需要使用自定义的方法。

理想情况下,我可以将ConnectionKeepAliveStrategy定义为常规bean,如果缺少它,只会使http客户端构建器保持不变。

2 个答案:

答案 0 :(得分:0)

没有意识到这很容易......

我只需要在配置中添加以下内容:

@Autowired(required = false)
public void customizeHttpClientBuilder(HttpClientBuilder httpClientBuilder, ConnectionKeepAliveStrategy keepAliveStrategy) {
  httpClientBuilder.setKeepAliveStrategy(keepAliveStrategy);
}

答案 1 :(得分:0)

使用java.util.Optional更简单的方法:

@Bean
@ConfigurationProperties(prefix = "http.client")
public HttpClientBuilder httpClientBuilder(Optional<ConnectionKeepAliveStrategy> keepAliveStrategy) {
    HttpClientBuilder builder = HttpClientBuilder.create();
    keepAliveStrategy.ifPresent(builder::setKeepAliveStrategy);
    return builder;
}