使用 Zuul 聚合多個微服務的 Swagger 文檔


在 Spring Boot 中集成 Swagger 可參考之前的文章:Spring Boot 2 集成 Swagger, 在各個微服務中的配置與之相同;本文僅介紹在 Zuul 中的配置

在 Zuul 項目中添加配置

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Autowired
    ZuulProperties properties;

    @Primary
    @Bean
    public SwaggerResourcesProvider swaggerResourcesProvider() {
        return () -> {
            List<SwaggerResource> resources = new ArrayList<>();
            properties.getRoutes().values().stream()
                    .forEach(route -> resources
                            .add(createResource(route.getServiceId(), route.getServiceId(), "2.0")));
            return resources;
        };
    }

    private SwaggerResource createResource(String name, String location, String version) {
        SwaggerResource swaggerResource = new SwaggerResource();
        swaggerResource.setName(name);
        swaggerResource.setLocation("/" + location + "/v2/api-docs");
        swaggerResource.setSwaggerVersion(version);
        return swaggerResource;
    }
}

其中 /v2/api-docs 為 Swagger 的 api

測試

訪問 http://localhost:8762/swagger-ui.html 即可看到效果 (8762 為 Zuul 項目的端口)

注意事項

  1. 各個微服務可以不引用 swagger-ui 依賴包,僅在 Zuul 項目引用即可
  2. 如果微服務中使用了Spring Security 需要放行 /v2/api-docs

參考:sample-zuul-swagger2

完整代碼:GitHub


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM