我正在使用发现第一个引导功能和Consul作为发现服务器,配置服务器的网址位于启动期间,我能够获得application.properties
。我还需要从配置服务器获取logback-spring.xml
配置,但我不知道如何。
我应该在属性logging.config={???}logback-spring.xml
指定什么才能不将 url 硬编码到配置服务器?
在 Consul 集成之前,我使用的是根据服务纯文本文档形成的 url,并在属性中使用硬编码的配置服务器 url,它工作正常,但现在我们想避免这种情况。
从我调试的内容来看,在 PropertySourceBootstrapConfiguration
中重新初始化日志记录系统期间没有使用发现客户端。
我使用自定义引导程序配置以"自定义"方式解决我的问题,因为我在文档和源代码中找不到解决方案。
示例:添加新文件src/main/resources/META-INF/spring.factories
并在那里添加自定义引导程序配置:org.springframework.cloud.bootstrap.BootstrapConfiguration=sample.custom.CustomPropertySourceLocator
在自定义属性源定位器中创建指向配置服务器 url 的属性(通过发现查找(
@Configuration
public class CustomPropertySourceLocator implements PropertySourceLocator {
private final String configServiceName;
private final DiscoveryClient discoveryClient;
public CustomPropertySourceLocator(
@Value("${spring.cloud.config.discovery.service-id}") String configServiceName,
DiscoveryClient discoveryClient){
this.configServiceName = configServiceName;
this.discoveryClient = discoveryClient;
}
@Override
public PropertySource<?> locate(Environment environment) {
List<ServiceInstance> instances = this.discoveryClient.getInstances(this.configServiceName);
ServiceInstance serviceInstance = instances.get(0);
return new MapPropertySource("customProperty",
Collections.singletonMap("configserver.discovered.uri", serviceInstance.getUri()));
}
}
在上面的代码中,我们创建了自定义属性源,该属性源将具有一个属性configserver.discovered.uri
。我们可以在我们的代码(使用 @Value(或其他属性文件中使用此属性(即使它们位于配置服务器存储中(。
logging.config=${configserver.discovered.uri}/<path to the text file>/logback-spring.xml
其中<path to text file>
应根据提供纯文本文档以及配置服务器的方式形成。