SpringCloud - GATEWAY与SWAGGER3的集成与使用

写在前面

在基于SpringCloud的项目中,各个微服务都有基于SWAGGER的在线API文档,所以将SWAGGER在线构建API文档创建了一个公共的场景启动器。如果要查看多个API文档怎么办呢? 一般会输入不同的IP:PORT查看不同微服务的文档,这样比较麻烦,所以将SWAGGER与GATEWAY进行聚合和集成,仅仅通过切换即可方便的查看。

操作步骤

1. 添加依赖
<!-- Swagger -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
</dependency>
2. 创建聚合系统接口
/**
 * 聚合系统接口
 * @author ROCKY
 */
@Component
@Primary
@AllArgsConstructor
public class SwaggerProvider implements SwaggerResourcesProvider {
    // SWAGGER3默认的URL后缀
    public static final String SWAGGER3URL = "/v3/api-docs";
    // 网关路由
    @Autowired
    private RouteLocator routeLocator;

    @Autowired
    private GatewayProperties gatewayProperties;

    // 聚合其他服务接口
    @Override
    public List<SwaggerResource> get() {
        List<SwaggerResource> resourceList = new ArrayList<>();
        List<String> routes = new ArrayList<>();
        // 获取网关中配置的route
        routeLocator.getRoutes().subscribe(route -> routes.add(route.getId()));
        gatewayProperties.getRoutes().stream()
                .filter(routeDefinition -> routes
                        .contains(routeDefinition.getId()))
                .forEach(routeDefinition -> routeDefinition.getPredicates().stream()
                        .filter(predicateDefinition -> "Path".equalsIgnoreCase(predicateDefinition.getName()))
                        .forEach(predicateDefinition -> resourceList
                                .add(swaggerResource(routeDefinition.getId(), predicateDefinition.getArgs()
                                        .get(NameUtils.GENERATED_NAME_PREFIX + "0").replace("/**", SWAGGER3URL)))));
        return resourceList;
    }

    private SwaggerResource swaggerResource(String name, String location) {
        SwaggerResource swaggerResource = new SwaggerResource();
        swaggerResource.setName(name);
        swaggerResource.setLocation(location);
        swaggerResource.setSwaggerVersion("3.0");
        return swaggerResource;
    }
}
3.创建swagger-resources的控制器
/**
 * SWAGGER-RESOURCES控制对象
 * @author ROCKY
 */
@RestController
@RequestMapping("/swagger-resources")
public class SwaggerHandler {
    @Autowired(required = false)
    private SecurityConfiguration securityConfiguration;

    @Autowired(required = false)
    private UiConfiguration uiConfiguration;

    private final SwaggerResourcesProvider swaggerResources;

    @Autowired
    public SwaggerHandler(SwaggerResourcesProvider swaggerResources) {
        this.swaggerResources = swaggerResources;
    }

    @GetMapping("/configuration/security")
    public Mono<ResponseEntity<SecurityConfiguration>> securityConfiguration() {
        return Mono.just(new ResponseEntity<>(
                Optional.ofNullable(securityConfiguration)
                        .orElse(SecurityConfigurationBuilder.builder().build()),
                HttpStatus.OK));
    }

    @GetMapping("/configuration/ui")
    public Mono<ResponseEntity<UiConfiguration>> uiConfiguration() {
        return Mono.just(new ResponseEntity<>(
                Optional.ofNullable(uiConfiguration)
                        .orElse(UiConfigurationBuilder.builder().build()), HttpStatus.OK));
    }

    @SuppressWarnings("rawtypes")
    @GetMapping("")
    public Mono<ResponseEntity> swaggerResources() {
        return Mono.just((new ResponseEntity<>(swaggerResources.get(), HttpStatus.OK)));
    }
}
4. APPLICATION.YML

在APPLICATION.YML需要进行以下配置,同时注意需要添加filters。

server:
  port: 8080
spring:
  application:
    name: servicex-gateway
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848
    gateway:
      globalcors:
        corsConfigurations:
          '[/**]':
            allowedOriginPatterns: "*"
            allowed-methods: "*"
            allowed-headers: "*"
            allow-credentials: true
            exposedHeaders: "Content-Disposition,Content-Type,Cache-Control"
      locator:
        enabled: true
        lowerCaseServiceId: true
      routes:
        # 唯一标识 - 系统核心服务
        - id: servicex-system
          uri: lb://servicex-system
          predicates:
            - Path=/api/servicex/system/**
          filters:
            - StripPrefix=3
        # 唯一标识 - 系统用户服务
        - id: servicex-user
          uri: lb://servicex-user
          predicates:
            - Path=/api/servicex/user/**
          filters:
            - StripPrefix=3
        # 唯一标识 - 商品服务
        - id: servicex-mallx-spu
          uri: lb://servicex-mallx-spu
          predicates:
            - Path=/api/servicex/mallx/spu/**
          filters:
            - StripPrefix=4
        # 唯一标识 - 订单服务
        - id: servicex-mallx-order
          uri: lb://servicex-mallx-order
          predicates:
            - Path=/api/servicex/mallx/order/**
          filters:
            - StripPrefix=4
4. 访问方式

http://网关IP:8080/swagger-ui/index.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
如果你想禁用Spring Cloud Gateway中的Swagger资源,可以在Gateway中添加一个过滤器来实现。 首先,在你的Gateway应用程序中,你需要创建一个过滤器类。这个过滤器将使用Spring Cloud Gateway中的RouteLocator来查找Swagger资源,然后将它们过滤掉。下面是一个示例过滤器类: ```java @Component public class SwaggerResourceFilter implements GlobalFilter, Ordered { @Autowired private RouteLocator routeLocator; @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { ServerHttpRequest request = exchange.getRequest(); String requestPath = request.getPath().toString(); // 获取所有的路由 List<Route> routes = routeLocator.getRoutes().collectList().block(); // 遍历路由,查找是否包含Swagger资源 for (Route route : routes) { String routePath = route.getUri().toString(); if (requestPath.startsWith(routePath) && route.getMetadata().containsKey("swagger")) { // 如果请求路径包含Swagger资源,直接返回 return Mono.empty(); } } // 如果请求路径不包含Swagger资源,继续执行过滤器链 return chain.filter(exchange); } @Override public int getOrder() { return -1; } } ``` 在这个过滤器类中,我们首先使用RouteLocator获取所有的路由,然后遍历这些路由,查找是否包含Swagger资源。如果请求路径包含Swagger资源,直接返回,否则继续执行过滤器链。 接下来,在你的Gateway配置文件中,添加以下代码来注册这个过滤器类: ```yaml spring: cloud: gateway: default-filters: - SwaggerResourceFilter ``` 这将会在Gateway启动时自动注册这个过滤器类。当你访问Swagger资源时,Gateway将会过滤掉这些资源,从而禁用它们。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

cloneme01

谢谢您的支持与鼓励!

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

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

打赏作者

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

抵扣说明:

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

余额充值