springboot微服务整合swagger3方法很简单,下文会演示。但是在分布式项目中如果每个微服务都需要单独的分开访问获取接口文档就不方便了,本文将详细讲解springcloud gateway网关如何聚合统一管理swagger接口文档。

先贴张整合后的效果图(通过切换左上角的下拉窗口获取每个微服务的接口文档):

一、swagger简介

  • 基于 OpenAPI 规范(OpenAPI Specification,OAS)构建的开源接口文档自动生成工具,可以让开发人员快速设计、构建、记录以及使用 Rest API。
  • 目前的版本有swagger2.0和3.0,swagger2于17年停止维护,现在最新的版本为17年发布的 Swagger3(Open Api3)。
  • Swagger 主要包含了以下三个部分:
    •   Swagger Editor:基于浏览器的编辑器,我们可以使用它编写我们 OpenAPI 规范。
    •   Swagger UI:它会将我们编写的 OpenAPI 规范呈现为交互式的 API 文档,后文我将使用浏览器来查看并且操作我们的 Rest API。
    •   Swagger Codegen:它可以通过为 OpenAPI(以前称为 Swagger)规范定义的任何 API 生成服务器存根和客户端 SDK 来简化构建过程。
  • SpringFox介绍(是 spring 社区维护的一个非官方项目)
    •   是一个开源的API Doc的框架,Marty Pitt编写了一个基于Spring的组件swagger-springmvc,用于将swagger集成到springmvc中来, 它的前身是swagger-springmvc,可以将我们的Controller中的方法以文档的形式展现。官方定义为: Automated JSON API documentation for API's built with Spring。

二、Springboot2.x整合Swagger3.x

首先看下单体微服务是如何整合swagger3的,事实上这也是后面gateway网关聚合统一文档的步骤之一。

步骤一:

SpringBoot添加pom文件依赖

  1. <dependency>
  2. <groupId>io.springfox</groupId>
  3. <artifactId>springfox-boot-starter</artifactId>
  4. <version>3.0.0</version>
  5. </dependency>

如果想让浏览器展示的UI效果更好看一点,需要引入最新的下面的依赖

  1. <!--swagger UI-->
  2. <dependency>
  3. <groupId>com.github.xiaoymin</groupId>
  4. <artifactId>knife4j-spring-ui</artifactId>
  5. <version>3.0.3</version>
  6. </dependency>

步骤二:

配置文件增加配置

  1. swagger:
  2. enable: true
  3. application-name: 鉴权配置中心接口
  4. application-version: 1.0
  5. application-description: 鉴权配置中心

步骤三:

创建配置类

  1. import org.springframework.boot.context.properties.ConfigurationProperties;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.stereotype.Component;
  4.  
  5. import io.swagger.annotations.ApiOperation;
  6. import lombok.Data;
  7. import springfox.documentation.builders.ApiInfoBuilder;
  8. import springfox.documentation.builders.PathSelectors;
  9. import springfox.documentation.builders.RequestHandlerSelectors;
  10. import springfox.documentation.oas.annotations.EnableOpenApi;
  11. import springfox.documentation.service.ApiInfo;
  12. import springfox.documentation.service.Contact;
  13. import springfox.documentation.spi.DocumentationType;
  14. import springfox.documentation.spring.web.plugins.Docket;
  15.  
  16. /**
  17. * @author: shf description: date: 2022/3/28 11:35
  18. */
  19. @Component
  20. @EnableOpenApi
  21. @ConfigurationProperties(prefix = "swagger")
  22. @Data
  23. public class SwaggerConfig {
  24.  
  25. /**
  26. * 是否开启swagger,生产环境一般关闭,所以这里定义一个变量
  27. */
  28. private Boolean enable;
  29.  
  30. /**
  31. * 项目应用名
  32. */
  33. private String applicationName;
  34.  
  35. /**
  36. * 项目版本信息
  37. */
  38. private String applicationVersion;
  39.  
  40. /**
  41. * 项目描述信息
  42. */
  43. private String applicationDescription;
  44.  
  45. @Bean
  46. public Docket docket() {
  47. return new Docket(DocumentationType.OAS_30)
  48. .pathMapping("/")
  49.  
  50. // 定义是否开启swagger,false为关闭,可以通过变量控制,线上关闭
  51. .enable(enable)
  52.  
  53. //配置api文档元信息
  54. .apiInfo(apiInfo())
  55.  
  56. // 选择哪些接口作为swagger的doc发布
  57. .select()
  58.  
  59. //apis() 控制哪些接口暴露给swagger,
  60. // RequestHandlerSelectors.any() 所有都暴露
  61. // RequestHandlerSelectors.basePackage("net.xdclass.*") 指定包位置
  62. // withMethodAnnotation(ApiOperation.class)标记有这个注解 ApiOperation
  63. .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
  64.  
  65. .paths(PathSelectors.any())
  66.  
  67. .build();
  68. }
  69.  
  70. private ApiInfo apiInfo() {
  71. return new ApiInfoBuilder()
  72. .title(applicationName)
  73. .description(applicationDescription)
  74. .contact(new Contact("鉴权中心平台接口文档", "www.yifeng.com", "123@qq.com"))
  75. .version(applicationVersion)
  76. .build();
  77. }
  78.  
  79. }

启动服务看下效果:

浏览器访问http://localhost:9799/doc.html

端口号是你服务配置指定的

三、gateway统一聚合

成功完成上面微服务整合swagger的步骤后,还需要在网关中增加配置

步骤一:

同样的引入依赖:

  1. <dependency>
  2. <groupId>io.springfox</groupId>
  3. <artifactId>springfox-boot-starter</artifactId>
  4. <version>3.0.0</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>com.github.xiaoymin</groupId>
  8. <artifactId>knife4j-spring-ui</artifactId>
  9. <version>3.0.3</version>
  10. </dependency>

步骤二:

配置文件:

  1. spring:
  2. cloud:
  3. gateway:
  4. globalcors:
  5. cors-configurations:
  6. '[/**]':
  7. allowCredentials: true
  8. allowedOrigins: "*"
  9. allowedMethods: "*"
  10. allowedHeaders: "*"
  11. routes:
  12. - filters:
  13. - RequestTime=true
  14. - StripPrefix=1
  15. id: core-route
  16. predicates:
  17. - Path=/core/**
  18. uri: xxxxxxxx
  19.  
  20. gateway-config:
  21. uriWhitelist:
  22. - /v3/api-docs

在网关的全局过滤器中要将配置的白名单放行。

步骤三:

添加路由枚举类,将上面配置文件中的每个微服务的路由ID替换为中文,即在UI页面的左上角显示的微服务文档名称。

  1. /**
  2. * 服务路由枚举
  3. *
  4. * @author shf
  5. * @date Created in 2022-03-28 16:28
  6. */
  7. public enum ServerRouteEnum {
  8.  
  9. /**
  10. * 路由信息
  11. */
  12. CORE_ROUTE("core-route", "开放平台鉴权配置接口");
  13.  
  14. private String routeId;
  15. private String swaggerInfo;
  16.  
  17. ServerRouteEnum(String routeId, String swaggerInfo) {
  18. this.routeId = routeId;
  19. this.swaggerInfo = swaggerInfo;
  20. }
  21.  
  22. /**
  23. * 根据路由id获取swagger信息
  24. *
  25. * @param routId 路由id
  26. * @return swagger信息
  27. */
  28. public static String getSwaggerInfoByRoutId(String routId) {
  29. for (ServerRouteEnum routeEnum : ServerRouteEnum.values()) {
  30. if (routId.equals(routeEnum.getRouteId())) {
  31. return routeEnum.getSwaggerInfo();
  32. }
  33. }
  34. return null;
  35. }
  36.  
  37. /**
  38. * @return the routeId
  39. */
  40. public String getRouteId() {
  41. return routeId;
  42. }
  43.  
  44. /**
  45. * @param routeId : the routeId to set
  46. */
  47. public void setRouteId(String routeId) {
  48. this.routeId = routeId;
  49. }
  50.  
  51. /**
  52. * @return the swaggerInfo
  53. */
  54. public String getSwaggerInfo() {
  55. return swaggerInfo;
  56. }
  57.  
  58. /**
  59. * @param swaggerInfo : the swaggerInfo to set
  60. */
  61. public void setSwaggerInfo(String swaggerInfo) {
  62. this.swaggerInfo = swaggerInfo;
  63. }
  64. }

最后一步:

新增配置类:

部分说明:

①SwaggerResource:处理的是UI页面中顶部的选择框,选择服务的swagger页面内容。

②RouteLocator:获取spring cloud gateway中注册的路由

  1. import org.apache.commons.lang3.StringUtils;
  2. import org.springframework.cloud.gateway.config.GatewayProperties;
  3. import org.springframework.cloud.gateway.route.RouteLocator;
  4. import org.springframework.cloud.gateway.support.NameUtils;
  5. import org.springframework.context.annotation.Primary;
  6. import org.springframework.stereotype.Component;
  7.  
  8. import java.util.ArrayList;
  9. import java.util.List;
  10.  
  11. import springfox.documentation.swagger.web.SwaggerResource;
  12. import springfox.documentation.swagger.web.SwaggerResourcesProvider;
  13.  
  14. /**
  15. * @author: shf description: date: 2022/3/28 14:16
  16. */
  17. @Component
  18. @Primary
  19. public class SwaggerProvider implements SwaggerResourcesProvider {
  20. public static final String API_URI = "/v3/api-docs";
  21. private final RouteLocator routeLocator;
  22. private final GatewayProperties gatewayProperties;
  23.  
  24. public SwaggerProvider(RouteLocator routeLocator, GatewayProperties gatewayProperties) {
  25. this.routeLocator = routeLocator;
  26. this.gatewayProperties = gatewayProperties;
  27. }
  28.  
  29. @Override
  30. public List<SwaggerResource> get() {
  31. List<SwaggerResource> resources = new ArrayList<>();
  32. List<String> routes = new ArrayList<>();
  33. // 取出gateway的route
  34. routeLocator.getRoutes().subscribe(route -> routes.add(route.getId()));
  35. // 结合配置的route-路径(Path),和route过滤,只获取在枚举中说明的route节点
  36. gatewayProperties.getRoutes().stream().filter(routeDefinition -> routes.contains(routeDefinition.getId()))
  37. .forEach(routeDefinition -> routeDefinition.getPredicates().stream()
  38. // 目前只处理Path断言 Header或其他路由需要另行扩展
  39. .filter(predicateDefinition -> ("Path").equalsIgnoreCase(predicateDefinition.getName()))
  40. .forEach(predicateDefinition -> {
  41. String routeId = routeDefinition.getId();
  42. String swaggerInfo = ServerRouteEnum.getSwaggerInfoByRoutId(routeId);
  43. if (StringUtils.isNotEmpty(swaggerInfo)) {
  44. resources.add(swaggerResource(swaggerInfo, predicateDefinition.getArgs().get(NameUtils.GENERATED_NAME_PREFIX + "0").replace("/**", API_URI)));
  45. }
  46. }
  47. ));
  48. return resources;
  49. }
  50.  
  51. private SwaggerResource swaggerResource(String name, String location) {
  52. SwaggerResource swaggerResource = new SwaggerResource();
  53. swaggerResource.setName(name);
  54. swaggerResource.setLocation(location);
  55. swaggerResource.setSwaggerVersion("3.0");
  56. return swaggerResource;
  57. }
  58.  
  59. }

浏览器访问:

旧版UI:http://localhost:9999/swagger-ui/index.html

新版UI:http://localhost:9999/doc.html

gateway聚合swagger3统一管理api文档的更多相关文章

  1. ASP.NET Web API 中使用 swagger 来管理 API 文档

    本文以 ASP.NET Web API 为后台框架,利用 EF6 连接 postgreSQL 数据库,使用 swagger 来生成 REST APIs文档.文章分二个部分,第一部分主要讲如何用 EF6 ...

  2. 微服务如何聚合 API 文档?这波秀~

    今天这篇文章介绍一下微服务如何聚合Swagger实现接口文档管理. 文章目录如下: 为什么需要聚合? 微服务模块众多,如果不聚合文档,则访问每个服务的API文档都需要单独访问一个Swagger UI界 ...

  3. API文档管理平台

    一.应用场景 在公司中,有很多开发,每个人维护的api接口是不一样的.如果有一个统一的api文档管理平台,每个开发,把自己维护的接口录入进去. 之后再开发别的功能时,不需要重复造轮子,直接调用就可以了 ...

  4. 随时发布:REST API文档的代码仓库中的持续集成与协作

    本文主要内容:API文档提供了预测客户成功的关键路径:在代码附近的文档上进行协作可以更好地检查代码和文档文件,提高自动化效率,并专门针对文档进行质量测试:提供通用文档框架,标准,自动化和工具,以提高团 ...

  5. 使用Swagger2Markup归档swagger生成的API文档

    文章出处: http://blog.didispace.com/swagger2markup-asciidoc/ 说明 项目中使用Swagger之后,我们能够很轻松的管理API文档,并非常简单的模拟接 ...

  6. springboot学习-jdbc操作数据库--yml注意事项--controller接受参数以及参数校验--异常统一管理以及aop的使用---整合mybatis---swagger2构建api文档---jpa访问数据库及page进行分页---整合redis---定时任务

    springboot学习-jdbc操作数据库--yml注意事项--controller接受参数以及参数校验-- 异常统一管理以及aop的使用---整合mybatis---swagger2构建api文档 ...

  7. REST api文档管理工具

    问题: 不同软件/程序在网络中互相传递信息不统一. 交互不便. REST API 作用: RESTful API就是一套协议,用来规范多种形式的前端和同一个后台的交互方式. 原理: 组成/流程/规范: ...

  8. 白话SpringCloud | 第十一章:路由网关(Zuul):利用swagger2聚合API文档

    前言 通过之前的两篇文章,可以简单的搭建一个路由网关了.而我们知道,现在都奉行前后端分离开发,前后端开发的沟通成本就增加了,所以一般上我们都是通过swagger进行api文档生成的.现在由于使用了统一 ...

  9. Swagger API文档集中化注册管理

    接口文档是前后端开发对接时很重要的一个组件.手动编写接口文档既费时,又存在文档不能随代码及时更新的问题,因此产生了像swagger这样的自动生成接口文档的框架.swagger文档一般是随项目代码生成与 ...

随机推荐

  1. 【Windows 访问控制】八、安全主体和安全对象

    安全主体(security principal)? 安全主体是任何可通过操作系统进行身份验证的实体,例如用户帐户.计算机帐户.在用户或计算机帐户的安全上下文中运行的线程或进程,或者这些帐户的安全组. ...

  2. 缓冲区(buffer)与缓存(cache) 缓冲:缓解冲击,缓存:临时存储

    缓存与缓冲区 简要概述 缓存(cache):故名思意就是临时存储一下数据的存储器,其他设备可能等下还用的到数据.缓存区可以用来做缓冲区 缓冲区(Buffer):故名意思就是解决设备之间速度不匹配的问题 ...

  3. .NET组件 vs. COM组件

    本文转载:https://www.cnblogs.com/larissa-0464/p/11095203.html 写在前面:我没有开发过COM组件的经验,只是在做文献综述的时候需要了解这方面的知识, ...

  4. 积分图(三) - Boxfilter 的实现过程分析

    Boxfilter 快速计算 它可以使复杂度为O(MN)的求和,求方差等运算降低到O(1)或近似于O(1)的复杂度,它的缺点是不支持多尺度. Boxfilter 的原理有点类似 Integral Im ...

  5. Flume介绍安装使用

    APache Flume官网:http://flume.apache.org/releases/content/1.9.0/FlumeUserGuide.html#memory-channel 目录 ...

  6. Linux命令大全(查看日志)

    1.查看日志常用命令     tail:          -n  是显示行号:相当于nl命令:例子如下:             tail -100f test.log      实时监控100行日 ...

  7. 30道关于linux的基础命令小题,先练练手

    1.修改主机名为yuanlai0224命令是: 2.切换⽬录到/yuchao01/data/,再创建脚本/my_website/scripts/start.sh. 绝对路径.相对路径两种写法 3.查看 ...

  8. MySQL 8.0.13(Windows压缩版本)下载安装教程

    MySQL下载安装教程 1.首先在百度上搜索mysql 2.点击链接进去,找到对应的路径 3.进去之后,可以看到版本是8.0.13,以及最下面有个Download按钮,点击下载 4.之后会跳转到开始下 ...

  9. vue全局引入公共scss样式,子组件调用

    前提 已引用并使用scss npm install sass-loader --save-dev npm install node-sass --sava-dev 配置 在vue.config.js中 ...

  10. 创建vue脚手架步骤

    一.在cmd配置npm淘宝镜像 npm config set registry https://registry.npm.taobao.org 二.仅第一次执行安装,安装好后关掉cmd后再开,这个时候 ...