我有3个微服务,所有这些都需要使用“公共”库。我需要向公共库添加新的Spring配置。问题在于,微服务A不在乎新代码,也不想被迫添加配置以使应用程序运行。我需要一种以编程方式仅针对微服务B和C加载配置的方法。
公共库中的新配置:
@Configuration
public class HttpConnectionConfiguration {
@Value("${http.connect.timeout}")
private int httpConnectTimeout;
@Value("${http.connect.request.timeout}")
private int httpConnectRequestTimeout;
@Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
restTemplate.setRequestFactory(getClientHttpRequestFactory());
return restTemplate;
}
private ClientHttpRequestFactory getClientHttpRequestFactory() {
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(httpConnectTimeout)
.setConnectionRequestTimeout(httpConnectRequestTimeout)
.build();
CloseableHttpClient client = HttpClientBuilder
.create()
.useSystemProperties()
.setDefaultRequestConfig(config)
.build();
return new HttpComponentsClientHttpRequestFactory(client);
}
}
application.yaml的微服务B和C中的配置:
http:
connect:
timeout: 5000
request:
timeout: 5000
微服务B和C正常启动,但是A给出此错误:Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'http.connect.timeout' in value "${http.connect.timeout}
在微服务A中不提供伪值的情况下解决此问题的最佳方法是什么?
答案 0 :(得分:1)
解决方案1:使用带有附加@Configuration
类的配置层次结构,该类构成一个RestTemplate
bean,并仅对B和C激活(或当该属性为可用):
@Configuration
@ConditionalOnProperty("http.connect.timeout")
public class HttpConnectionConfiguration {
// rest of code ...
解决方案2:使用默认值。自default timeout is -1
起,使用:
@Value("${http.connect.timeout:-1}")
private int httpConnectTimeout;
@Value("${http.connect.request.timeout:-1}")
private int httpConnectRequestTimeout;
答案 1 :(得分:0)
您可以使用如下所示的SpEL表达式在@Value
中指定默认值。
@Value("${http.connect.timeout:10}")
private int httpConnectTimeout;
@Value("${http.connect.request.timeout:10}")
private int httpConnectRequestTimeout;