Как получить список файлов, управляемых Spring-Cloud-Config-Server

У меня запущено 3 приложения Spring-Boot:

  1. Эврика:8761
  2. Spring-Cloud-Config:8080
  3. моймикросервис: 8181

Для Spring-Cloud-Config я использую локальный URI git для заполнения данных. Локальный репозиторий находится в ветке master и имеет такую ​​файловую структуру:

./myMicroService
  |-- application.properties
  |-- foo.txt
  |-- bar.txt

Согласно документация, я могу получить доступ к текстовым файлам следующим образом:

http://локальный:8080/myMicroService/по умолчанию/мастер/foo.txthttp://локальный:8080/myMicroService/по умолчанию/мастер/бар.txt

Что работает, но как получить полный список доступных файлов *.txt, обслуживаемых сервером Spring-Cloud-Config?

Я пробовал это:

http://локальный:8080/myMicroService/по умолчанию/мастер

Который возвращает только application.properties и его значения.

Сейчас нет способа сделать это.

spencergibb 12.04.2019 21:09
Пользовательский скаляр GraphQL
Пользовательский скаляр GraphQL
Листовые узлы системы типов GraphQL называются скалярами. Достигнув скалярного типа, невозможно спуститься дальше по иерархии типов. Скалярный тип...
Как вычислять биты и понимать побитовые операторы в Java - объяснение с примерами
Как вычислять биты и понимать побитовые операторы в Java - объяснение с примерами
В компьютерном программировании биты играют важнейшую роль в представлении и манипулировании данными на двоичном уровне. Побитовые операции...
Поднятие тревоги для долго выполняющихся методов в Spring Boot
Поднятие тревоги для долго выполняющихся методов в Spring Boot
Приходилось ли вам сталкиваться с требованиями, в которых вас могли попросить поднять тревогу или выдать ошибку, когда метод Java занимает больше...
Полный курс Java для разработчиков веб-сайтов и приложений
Полный курс Java для разработчиков веб-сайтов и приложений
Получите сертификат Java Web и Application Developer, используя наш курс.
3
1
3 476
2
Перейти к ответу Данный вопрос помечен как решенный

Ответы 2

Ответ принят как подходящий

Учитывая, что для этого нет решения 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"
]

В предыдущем решении предполагается, что ваш spring.cloud.config.server.git.uri имеет тип https. Приведенное ниже решение будет ссылаться на локальную файловую систему, содержащую файлы, извлеченные из репозитория, и будет работать с любым типом репо. Конечные точки также принимают путь поиска и имеют формат:

  • /{name}/{profile}/{label}/{path}/listFiles
  • /{name}/{profile}/{path}/listFiles?useDefaultLabel
@Configuration
@EnableAutoConfiguration
@EnableConfigServer
@RestController
public class CloudConfigApplication {

    private UrlPathHelper helper = new UrlPathHelper();

    private SearchPathLocator service;

    public static void main(String[] args) {
        SpringApplication.run(CloudConfigApplication.class, args);
    }

    public CloudConfigApplication(SearchPathLocator service) {
        this.service = service;
    }

    @RequestMapping("/{name}/{profile}/{label}/**/listFiles")
    public List<String> retrieve(@PathVariable String name, @PathVariable String profile,
                                 @PathVariable String label, ServletWebRequest request,
                                 @RequestParam(defaultValue = "true") boolean resolvePlaceholders)
            throws IOException {
        String path = getDirPath(request, name, profile, label);
        return listAll(request, name, profile, label, path);
    }

    @RequestMapping(value = "/{name}/{profile}/**/listFiles", params = "useDefaultLabel")
    public List<String> retrieve(@PathVariable String name, @PathVariable String profile,
                                 ServletWebRequest request,
                                 @RequestParam(defaultValue = "true") boolean resolvePlaceholders)
            throws IOException {
        String path = getDirPath(request, name, profile, null);
        return listAll(request, name, profile, null, path);
    }

    private String getDirPath(ServletWebRequest request, String name, String profile, String label) {
        String stem;
        if (label != null) {
            stem = String.format("/%s/%s/%s/", name, profile, label);
        } else {
            stem = String.format("/%s/%s/", name, profile);
        }
        String path = this.helper.getPathWithinApplication(request.getRequest());
        path = path.substring(path.indexOf(stem) + stem.length()).replace("listFiles", "");
        return path;
    }

    public synchronized List<String> listAll(ServletWebRequest request, String application, String profile, String label, String path) {
        if (StringUtils.hasText(path)) {
            String[] locations = this.service.getLocations(application, profile, label).getLocations();
            List<String> fileURIs = new ArrayList<>();

            try {
                int i = locations.length;

                while (i-- > 0) {
                    String location = String.format("%s%s", locations[i], path).replace("file:", "");
                    Path filePath = new File(location).toPath();
                    if (Files.exists(filePath)) {
                        fileURIs.addAll(Files.list(filePath).filter(file -> !Files.isDirectory(file)).map(file -> {
                            String URL =
                                    String.format(
                                            "%s://%s:%d%s/%s/%s/%s%s?useDefaultLabel",
                                            request.getRequest().getScheme(), request.getRequest().getServerName(),
                                            request.getRequest().getServerPort(), request.getRequest().getContextPath(),
                                            application, profile, path,
                                            file.getFileName().toString());
                            if (label != null) {
                                URL = String.format(
                                        "%s://%s:%d%s/%s/%s/%s/%s%s",
                                        request.getRequest().getScheme(), request.getRequest().getServerName(),
                                        request.getRequest().getServerPort(), request.getRequest().getContextPath(),
                                        application, profile, label, path,
                                        file.getFileName().toString());
                            }
                            return URL;
                        }).collect(Collectors.toList()));
                    }
                }
            } catch (IOException var11) {
                throw new NoSuchResourceException("Error : " + path + ". (" + var11.getMessage() + ")");
            }
            return fileURIs;
        }
        throw new NoSuchResourceException("Not found: " + path);
    }
}

Получение списка:

curl http://localhost:8080/context/appName/profile/label/some/path/listFiles

Пример результатов:

[
   "http://localhost:8080/context/appName/profile/label/some/path/robots.txt"
]

Другие вопросы по теме