Spring Cloud项目Gateway统一管理swagger接口

Spring Cloud项目Gateway统一管理swagger接口

一、前提

1.是Spring Cloud 项目
2. 整合了nacos
SpringCloud 项目整合Nacos详细步骤 —https://blog.csdn.net/weixin_45941687/article/details/126124313
3.整合了Spring Gateway组件
4.除了Gateway服务,其他子业务服务,都引入了Swagger配置
子服务引入swagger – https://blog.csdn.net/weixin_45941687/article/details/126034380

二、在Gateway服务添加Swagger配置

2.1 pom.xml引入swagger的依赖

            <!--swagger本身不支持spring mvc的,springfox把swagger包装了一下,让他可以支持springmvc-->
            <!-- swagger-ui -->
            <dependency>
                <groupId>io.springfox</groupId>
                <artifactId>springfox-swagger-ui</artifactId>
                <version>2.9.2</version>
            </dependency>

            <!-- swagger2 -->
            <dependency>
                <groupId>io.springfox</groupId>
                <artifactId>springfox-swagger2</artifactId>
                <version>2.9.2</version>
            </dependency>

2.2 修改bootstrap.yml文件,登录nacos,修改网关的配置文件

# 根据自己的服务去配置相关数据
spring:
  cloud:
    gateway:
      routes:
          # 配置id唯一
        - id: auth 
          # 配置要跳转的微服务的路径 lb:表示协议loadbalance
          uri: lb://sign-auth
          # 断言 当请求路径是auth的时候 进行auth微服务的跳转 配置对于哪些请求进行此微服务的跳转
          predicates: 
            - Path=/auth/**
          filters:
            # StripPrefix 过滤器
            # PrefixPath 过滤器  和StripPrefix正相反,是在URL路径前面添加一部分的前缀
            - StripPrefix=1
        - id: work
          uri: lb://sign-work
          predicates:
            - Path=/work/**
          filters: 
            - StripPrefix=1 

2.3 添加SwaggerProvider配置文件

package com.luck.sign.config;

import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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 org.springframework.web.reactive.config.ResourceHandlerRegistry;
import org.springframework.web.reactive.config.WebFluxConfigurer;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;

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

/**
 * 聚合每个服务的接口
 */
@Component
@Primary
public class SwaggerProvider implements SwaggerResourcesProvider, WebFluxConfigurer {

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


    /**
     * 网关路由
     */
    @Autowired
    private  RouteLocator routeLocator;

    @Autowired
    private GatewayProperties gatewayProperties;

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

    public SwaggerProvider() {
    }


    /**
     * 聚合其他服务接口
     *
     * @return
     */
    @Override
    public List<SwaggerResource> get()
    {
        List<SwaggerResource> resourceList = new ArrayList<>();
        List<String> routes = new ArrayList<>();

        // 获取网关中配置的route
        routeLocator.getRoutes()
                .filter(route -> route.getUri().getHost() != null)
                .filter(route -> !self.equals(route.getUri().getHost()))
                .subscribe(route -> routes.add(route.getId()));

        // 记录已经添加过的server,存在同一个应用注册了多个服务在nacos上
//          .filter(predicateDefinition -> "Path".equalsIgnoreCase(predicateDefinition.getName()))
        gatewayProperties.getRoutes().stream().filter(routeDefinition -> routes.contains(routeDefinition.getId()))
                .forEach(routeDefinition -> routeDefinition.getPredicates().stream()
                        .forEach(predicateDefinition -> resourceList.add(
                                swaggerResource(
                                        routeDefinition.getId(),
                                        predicateDefinition
                                                .getArgs()
                                                .get(NameUtils.GENERATED_NAME_PREFIX + "0")
                                                .replace("/**",SWAGGER2URL)
                                )
                        )));
        return resourceList;
    }

    private SwaggerResource swaggerResource(String name, String location)
    {
        SwaggerResource swaggerResource = new SwaggerResource();
        swaggerResource.setName(name);
        swaggerResource.setLocation(location);
        swaggerResource.setSwaggerVersion("2.0");
        return swaggerResource;
    }

    /**
     * 设置静态资源映射(WebMvcConfig类中的addResourceHandlers方法) ,否则接口文档页面无法访问
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry)
    {
        /** swagger-ui 地址 */
        registry.addResourceHandler("/swagger-ui/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/");
    }

}

2.4 添加SwaggerResourceController配置文件

package com.luck.sign.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.route.RouteLocator;
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;

@RestController
@RequestMapping("/swagger-resources")
public class SwaggerResourceController {
    private SwaggerProvider swaggerResourceProvider;

    @Autowired
    public SwaggerResourceController(SwaggerProvider swaggerResourceProvider) {
        this.swaggerResourceProvider = 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);
    }

}

三、学习链接

1.spring cloud微服务使用swagger2接口文档 – https://blog.csdn.net/bai_shuang/article/details/121762432

2.springcloud-gateway网关聚合swagger实现多个服务接口聚合 – https://blog.csdn.net/liuyunshengsir/article/details/118111670

3.Spring Cloud Gateway整合Swagger聚合微服务系统API文档(非Zuul) – https://blog.csdn.net/ttzommed/article/details/81103609

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值