首页 > 解决方案 > Spring API 网关中的 Swagger Api 文档

问题描述

w

我在项目中有上述架构。Product、Order、Payment 微服务是一个 Rest API,目前具有 swagger 集成,但现在流程发生了变化,我无法公开微服务 Rest API 现在所有 REST API 调用都是从 API 网关进行的。

有没有办法通过 API 网关在 swagger 中记录 API,或者这种情况下的最佳实践是什么。

这是 API Gateway Spring boot 中的路由配置

@Bean
    public RouteLocator gatewayRoutes(RouteLocatorBuilder builder) {
        return builder.routes()
                .route(r -> r.path("/order/**")
                        .filters(f -> f.hystrix(option -> option.setName("order-service").
                                setFallbackUri("forward:/orderFallBack")))
                        .uri("lb://ORDER-SERVICE")
                        .id("order-service"))

                .route(r -> r.path("/payment/**")
                        .filters(f -> f.hystrix(option -> option.setName("payment-service")
                                .setFallbackUri("forward:/paymentFallBack")))
                        .uri("lb://PAYMENT-SERVICE")
                        .id("payment-service"))

                .route(r -> r.path("/product/**")
                        .filters(f -> f.hystrix(option -> option.setName("product-service")
                                .setFallbackUri("forward:/productFallBack")))
                        .uri("lb://PRODUCT-SERVICE")
                        .id("product-service"))
                .build();
    }

Order 微服务项目中的 Swagger 配置

@Configuration
public class SwaggerConfiguration {
    @Bean
    public Docket orderApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
                .paths(PathSelectors.any())
                .build()
                .apiInfo(getApiInfo());
    }

    //create api metadata that goes at the top of the generated page
    private ApiInfo getApiInfo() {
        return new ApiInfoBuilder()
                .title("Fete Bird Order Microservice")
                .version("1.0")
                .description("API for managing Fete Bird Order Microservice.")
                .license("Fete Bird License Version 1.0")
                .build();
    }
}

在此处输入图像描述

标签: javaspringspring-bootswaggerspringfox

解决方案


有一种常见的做法是让网关本身可以使用各个 swagger 端点。我已经在许多生产级项目中看到了这一点。

例如,对于订单服务,文档将位于:

http://gateway-url/order-service/swagger-ui.html

其他微服务也可以采用类似的方法。


推荐阅读