Spring Cloud Gateway 整合 Swagger3.0

Swagger3.0介绍
Github地址: https://github.com/springfox/springfox/releases

  • 选用3.x版本以上, 当前最新3.0.0
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>
  • Spring Cloud Gateway整合Swagger3.x常见有两种方式:

a. 通过服务注册中心(Nacos或Euraka)来扫描所有当前启用的服务来生成文档,
    b. 通过gateway的网关配置来扫描服务
    本次采用的是第二种:
    1. 修改配置文件application.yml,在gateway配置中将swagger相关访问资源给排除

excludeUrls: "v2/api-docs,/swagger-resources/**,/swagger-ui.html**,/webjars/**,/swagger-ui/**"

2. 新增GatewaySwaggerProvider.java,实现对所有注册服务的资源托管

@Component
@Primary
public class GatewaySwaggerProvider implements SwaggerResourcesProvider {

    /**
     * swagger2默认的url后缀, gateway目前对OAS_30支持尚不完善,此处仍使用swagger2.0的文件类型
     */
    private static final String SWAGGER2_URL = "/v2/api-docs";

    @Autowired
    private RouteLocator routeLocator;

    /**
     * 网关应用名称
     */
    @Value("${spring.application.name}")
    private String self;

    @Override
    public List<SwaggerResource> get() {
        List<SwaggerResource> resources = new ArrayList<>();
        List<String> routeHosts = new ArrayList<>();
        routeLocator.getRoutes()
                .filter(route -> route.getUri().getHost() != null)
                .filter(route -> route.getUri().getHost() != null)
                .filter(route -> Objects.equals(route.getUri().getScheme(), "lb"))
                //过滤掉网关自身的服务  uri中的host就是服务id
                .filter(route -> !self.equalsIgnoreCase(route.getUri().getHost()))
                .subscribe(route -> routeHosts.add(route.getUri().getHost()));

        // 记录已经添加过的server,存在同一个应用注册了多个服务在注册中心上
        Set<String> dealed = new HashSet<>();
        routeHosts.forEach(instance -> {
            // 拼接url ,请求swagger的url
            String url = "/" + instance.toLowerCase() + SWAGGER2_URL;
            if (!dealed.contains(url)) {
                dealed.add(url);
                SwaggerResource swaggerResource = new SwaggerResource();
                swaggerResource.setUrl(url);
                swaggerResource.setName(instance);
                resources.add(swaggerResource);
            }
        });
        return resources;
    }
}

3.  其他子服务模块添加swagger配置, 主要设置文档说明和请求头参数

@Configuration
@EnableOpenApi
public class SwaggerConfig {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.OAS_30)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.nacos.demo.order"))
                .paths(PathSelectors.any())
                .build()
                .globalRequestParameters(globalRequestParameters())
                .apiInfo(apiInfo());
    }

    /**
     * 请求头配置
     * @return
     */
    private List<RequestParameter> globalRequestParameters() {
        RequestParameterBuilder parameterBuilder = new RequestParameterBuilder()
                .in(ParameterType.HEADER).name("Token").required(true)
                .query(param -> param.model(model -> model.scalarModel(ScalarType.STRING)));
        return Collections.singletonList(parameterBuilder.build());
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("订单服务API")
                .description("订单管理文档API")
                .version("1.0")
                .build();
    }
}
  • 启动所有服务gateway、user、order

访问gateway地址:http://localhost:8081/swagger-ui/index.html
image.png

暂无评论