我正在运行3个Spring-Boot应用程序:
尤里卡:8761
春季云配置:8080
myMicroService:8181
对于Spring-Cloud-Config,我使用本地git URI填充数据。本地存储库位于分支master
上,并具有如下文件结构:
./myMicroService
|-- application.properties
|-- foo.txt
|-- bar.txt
根据documentation,我可以像这样访问文本文件:
http://localhost:8080/myMicroService/default/master/foo.txt
http://localhost:8080/myMicroService/default/master/bar.txt
哪个可行,但是如何获取Spring-Cloud-Config服务器提供的可用* .txt文件的完整列表?
我尝试了这个:
http://localhost:8080/myMicroService/default/master
仅返回
application.properties
及其值。 最佳答案
鉴于没有针对此的OOTB解决方案,我向配置服务器添加了一个新的请求映射:
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.config.server.EnableConfigServer;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@EnableConfigServer
@EnableEurekaClient
@RestController
public class ConfigServer {
public static void main(String[] args) {
SpringApplication.run(ConfigServer.class, args);
}
@Value("${spring.cloud.config.server.git.uri}")
private String uri;
@Autowired private ResourceLoader resourceLoader;
@GetMapping("/{name}/{profile}/{label}/listFiles")
public Collection<String> retrieve(
@PathVariable String name,
@PathVariable String profile,
@PathVariable String label,
HttpServletRequest request)
throws IOException {
Resource resource = resourceLoader.getResource(uri);
String uriPath = resource.getFile().getPath();
Path namePath = Paths.get(uriPath, name);
String baseUrl =
String.format(
"http://%s:%d/%s/%s/%s",
request.getServerName(), request.getServerPort(), name, profile, label);
try (Stream<Path> files = Files.walk(namePath)) {
return files
.map(Path::toFile)
.filter(File::isFile)
.map(File::getName)
.map(filename -> baseUrl + "/" + filename)
.collect(Collectors.toList());
}
}
}
获取myMicroService的文件列表:
curl http://localhost:8888/myMicroService/default/master/listFiles
结果:
[
"http://localhost:8888/myMicroService/default/master/application.properties",
"http://localhost:8888/myMicroService/default/master/foo.txt",
"http://localhost:8888/myMicroService/default/master/bar.txt"
]