Spring Cloud Gateway②聚合Swagger

背景

各个微服务都有自己的Swagger文档,当使用Gateway做为微服务统一入口时,如何对外统一暴露微服务的Swagger呢?这篇文章继续演示Gateway聚合各个微服务的Swagger的能力,以最小依赖为原则,不依赖注册中心,以便聚焦如何展示Swagger这部分的功能。

本文开发环境介绍

开发依赖版本
Spring Boot2.7.0
Spring Cloud2021.0.1
Spring Cloud Alibaba2021.0.1.0

搭建一个微服务

微服务需要提供Swagger

pom.xml的依赖如下

    <properties>
        <springfox-boot-starter.version>3.0.0</springfox-boot-starter.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>${springfox-boot-starter.version}</version>
        </dependency>
    </dependencies>

开启Swagger

import io.swagger.annotations.Api;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

@Configuration
@EnableOpenApi
public class SwaggerAutoConfiguration {

    @Bean
    public Docket onlineDocApi() {
        return new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo("Controller接口", "接口文档", "1.0"))
                .select()
                .apis( RequestHandlerSelectors.withClassAnnotation(Api.class))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo(String name, String description, String version) {
        return new ApiInfoBuilder()
                .title(name)
                .description(description)
                .contact(new Contact("demo", null, null))
                .version(version).build();
    }
}

application.yml如下

server:
  port: 8082
spring:
  mvc:
    pathmatch:
      matching-strategy: ant_path_matcher

运行main函数启动微服务

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SwaggerDemoApplication {

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

访问微服务Swagger

在浏览器输入http://localhost:8082/swagger-ui/index.html
在这里插入图片描述
说明这个微服务的Swagger已经正常开启了

Gateway入门

如果还不熟悉Gateway的可以参考上一篇写的Gateway入门

Gateway配置

pom.xml依赖

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>${springfox-boot-starter.version}</version>
        </dependency>
    </dependencies>

转发配置示例

application.yml配置如下

server:
  port: 8081
spring:
  application:
    name: demo-gateway
  mvc:
    pathmatch:
      matching-strategy: ant_path_matcher
  cloud:
    gateway:
      #路由配置
      routes:
        - id: demoSwagger
          uri: http://localhost:8082
          predicates:
            - Path=/demo/**
          filters:
            - StripPrefix=1

实现SwaggerResourcesProvider接口

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.config.GatewayProperties;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.support.NameUtils;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;

import java.util.ArrayList;
import java.util.List;

@RequiredArgsConstructor
@Slf4j
@Component
@Primary
public class SwaggerProvider implements SwaggerResourcesProvider {

    /**swagger2默认的url后缀*/
    private static final String SWAGGER_URI = "/v2/api-docs";

    private final RouteLocator routeLocator;
    private final GatewayProperties gatewayProperties;

    @Override
    public List<SwaggerResource> get() {
        List<SwaggerResource> resources = new ArrayList<>();
        List<String> routes = new ArrayList<>();
        // 只抽取后缀为Swagger的路由信息
        routeLocator.getRoutes()
                .filter(route -> route.getId().endsWith("Swagger"))
                .subscribe(route -> routes.add(route.getId()));

        gatewayProperties.getRoutes().stream().filter(routeDefinition -> routes.contains(routeDefinition.getId())).forEach(route -> {
            route.getPredicates().stream()
                    .filter(predicateDefinition -> ("Path").equalsIgnoreCase(predicateDefinition.getName()))
                    .forEach(predicateDefinition -> resources.add(swaggerResource(route.getId(),
                            predicateDefinition.getArgs().get(NameUtils.GENERATED_NAME_PREFIX + "0")
                                    .replace("/**", SWAGGER_URI))));
        });
        return resources;
    }

    private SwaggerResource swaggerResource(String name, String location) {
        log.info("name:{},location:{}",name,location);
        SwaggerResource swaggerResource = new SwaggerResource();
        swaggerResource.setName(name);
        swaggerResource.setLocation(location);
        return swaggerResource;
    }
}

重写Swagger的数据接口

import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.swagger.web.*;

import java.util.List;

@RequiredArgsConstructor
@RestController
@RequestMapping("/swagger-resources")
public class SwaggerResourceController {

    private final SwaggerProvider swaggerResourceProvider;

    @RequestMapping(value = "/configuration/security")
    public ResponseEntity<SecurityConfiguration> securityConfiguration() {
        return new ResponseEntity<>(SecurityConfigurationBuilder.builder().build(), HttpStatus.OK);
    }

    @RequestMapping(value = "/configuration/ui")
    public ResponseEntity<UiConfiguration> uiConfiguration() {
        return new ResponseEntity<>(UiConfigurationBuilder.builder().build(), HttpStatus.OK);
    }

    @RequestMapping
    public ResponseEntity<List<SwaggerResource>> swaggerResources() {
        return new ResponseEntity<>(swaggerResourceProvider.get(), HttpStatus.OK);
    }
}

启动类

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import springfox.documentation.oas.annotations.EnableOpenApi;

@EnableOpenApi
@SpringBootApplication
public class DemoGatewayApplication {

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

Swagger访问测试

在浏览器输入http://localhost:8081/swagger-ui
在这里插入图片描述

看到的Swagger8082端口的微服务是一样的

总结

我们在开发微服务的过程中,由于各种原因,会引入API网关,那么之前直接由微服务对外提供的Swagger文档,也同样希望可以通过API网关统一对外展示,本文通过最小依赖,使用极简的方式演示了Gateway如何聚合后端微服务的Swagger文档,希望可以帮助到大家少走一点弯路。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

太空眼睛

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值