【问题标题】:Unable to get logback-spring.xml property file using Spring Cloud Config and Discovery无法使用 Spring Cloud Config 和 Discovery 获取 logback-spring.xml 属性文件
【发布时间】:2018-09-23 23:12:22
【问题描述】:
我使用Discovery first bootstrap 功能和Consul 作为发现服务器,配置服务器的URL 位于启动期间,我能够获得application.properties。我还需要从配置服务器获取logback-spring.xml 配置,但我不知道如何。
我应该在logging.config={???}logback-spring.xml 属性中指定什么来不对配置服务器的 url 进行硬编码?
在 Consul 集成之前,我使用根据 Serving Plain text documentation 形成的 url,在属性中带有硬编码的配置服务器 url,它工作正常,但现在我们想避免这种情况。
根据我的调试,在PropertySourceBootstrapConfiguration 重新初始化日志系统期间没有使用发现客户端。
【问题讨论】:
标签:
spring-boot
logback
spring-cloud-config
spring-cloud-consul
spring-logback
【解决方案1】:
我使用Customizing Bootstrap Configuration 以“自定义”方式解决我的问题,因为我没有在文档和源代码中找到解决方案。
示例:添加新文件 src/main/resources/META-INF/spring.factories 并在其中添加自定义引导配置:org.springframework.cloud.bootstrap.BootstrapConfiguration=sample.custom.CustomPropertySourceLocator
在 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> 应根据Serving Plain Text Documentation 以及您配置配置服务器的方式形成。