我喜欢这样(尚未完成):我有 spring.cloud.config.server.native.serach-locations 以逗号分隔的 URI 列表形式
file:/c:/repo/a,file:/c:/repo/b
我创建了 FileMonitorConfiguration bean(但它有一些问题,因为它被调度了 2 次,一个 bean 本身和一个 spring 增强实例,我不熟悉这个)
并实现(只是草稿) NativePropertyPathNotificationExtractor
@Configuration
@EnableAutoConfiguration
@EnableConfigServer
public class ConfigServerApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigServerApplication.class, args);
}
@Bean
NativePropertyPathNotificationExtractor nativePropertyPathNotificationExtractor(@Autowired(required = false) NativeEnvironmentRepository nativeRepo) {
return new NativePropertyPathNotificationExtractor(nativeRepo);
}
@Bean
FileMonitorConfiguration fileMonitorConfiguration() {
return new FileMonitorConfiguration();
}
}
@Order(Ordered.LOWEST_PRECEDENCE - 500)
public class NativePropertyPathNotificationExtractor implements PropertyPathNotificationExtractor {
private final Set<Path> searchPaths;
public NativePropertyPathNotificationExtractor(NativeEnvironmentRepository nativeRepo) {
searchPaths = searchLocations(nativeRepo);
}
@Override
public PropertyPathNotification extract(MultiValueMap<String, String> headers, Map<String, Object> payload) {
// FileMonitor with empty headers, so if some there, ignore
if (false == headers.isEmpty()) {
return null;
}
if (null == searchPaths) {
return null;
}
Path path = pathFromPayload(payload);
if (null == path) {
return null;
}
for (Path searchPath : searchPaths) {
Path relative = searchPath.relativize(path);
// just a try ;-)
if (true == relative.startsWith("..")) {
continue;
}
return new PropertyPathNotification(relative.toString());
}
return null;
}
private Path pathFromPayload(Map<String, Object> payload) {
if (null == payload) {
return null;
}
if (true == payload.isEmpty()) {
return null;
}
if (false == payload.containsKey("path")) {
return null;
}
if (null == payload.get("path")) {
return null;
}
if (true == StringUtils.isEmpty(payload.get("path").toString())) {
return null;
}
return Paths.get(payload.get("path").toString()).normalize().toAbsolutePath();
}
private Set<Path> searchLocations(NativeEnvironmentRepository nativeRepo) {
if (null == nativeRepo) {
return null;
}
if (null == nativeRepo.getSearchLocations()) {
return null;
}
final Set<Path> paths = new LinkedHashSet<>();
for (String location : nativeRepo.getSearchLocations()) {
try {
paths.add(Paths.get(new URI(location)).normalize().toAbsolutePath());
} catch (Exception e) {
System.err.println("Nevalidne search location uri: " + location);
}
}
return paths;
}
}