OK,这一篇博客继续讲解 Swagger 整合到 SpringCloud Gateway。

我们使用 swagger-spring-boot-starter 版本,可以查看 Maven 官网:https://mvnrepository.com/artifact/com.spring4all/swagger-spring-boot-starter

我们搭建一个完整的 demo,包括注册中心 Eureka(端口8080),网关 Gateway(端口80),2个微服务:产品微服务(端口1001)、订单微服务(端口1002)。代码结构如图:

这里只说重点部分,可以先下载代码:https://pan.baidu.com/s/17XKJEwNLpcxf-7PtmbOU_Q  提取码:f7b3

最外层 pom.xml 配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.study</groupId><artifactId>swagger-gateway</artifactId><packaging>pom</packaging><version>1.0-SNAPSHOT</version><modules><module>eureka-server</module><module>gateway-server</module><module>product-server</module><module>order-server</module></modules><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.2.2.RELEASE</version></parent><properties><!-- 配置 Swagger 版本 --><swagger.version>1.9.0.RELEASE</swagger.version></properties><dependencies><!--Spring boot 集成包--><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-eureka-client</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><!-- swagger-start 依赖。https://mvnrepository.com/artifact/com.spring4all/swagger-spring-boot-starter --><dependency><groupId>com.spring4all</groupId><artifactId>swagger-spring-boot-starter</artifactId><version>${swagger.version}</version></dependency><!-- lombok 依赖 --><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency></dependencies><dependencyManagement><dependencies><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-dependencies</artifactId><version>Hoxton.SR2</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement></project>

然后说一下产品服务的代码,订单服务是一样的,不赘述。

product-server 的 pom.xml 配置:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><parent><artifactId>swagger-gateway</artifactId><groupId>com.study</groupId><version>1.0-SNAPSHOT</version></parent><modelVersion>4.0.0</modelVersion><artifactId>product-server</artifactId><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency></dependencies></project>

实体类:

package com.study.entity;import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.*;/*** @author biandan* @description* @signature 让天下没有难写的代码* @create 2021-06-06 下午 5:45*/
@Data
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor(staticName = "of")
@Builder
@ApiModel(description = "产品实体类")
public class ProductEntity {@ApiModelProperty(value = "产品ID")private Integer productId;@ApiModelProperty(value = "产品名称")private String productName;}

控制层:只需要添加注解 @EnableSwagger2Doc 即可,因为 SpringBoot 已经帮我们整合配置了,不需要 SwaggerConfig 类!

package com.study.controller;import com.spring4all.swagger.EnableSwagger2Doc;
import com.study.entity.ProductEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;/*** @author biandan* @description* @signature 让天下没有难写的代码* @create 2021-06-06 下午 5:45*/
@RestController
@Api(tags = "产品信息管理 API 接口文档")
@RequestMapping("/api/product")
@EnableSwagger2Doc //SpringBoot 已经整合好 swagger 的相关配置了
public class ProductController {@PostMapping("/getProductInfo")@ApiOperation(value = "查询产品信息接口", notes = "这是一段方法的描述")@ApiImplicitParams({@ApiImplicitParam(name = "productId", value = "产品Id", required = false, dataType = "Integer"),@ApiImplicitParam(name = "productName", value = "产品名称", required = true, dataType = "String")})public ProductEntity getInfo(@RequestParam(value = "productId",required = false) Integer productId,@RequestParam("productName") String productName) {ProductEntity productEntity = new ProductEntity();productEntity.setProductId(123);productEntity.setProductName("霸王防脱洗发液");return productEntity;}
}

如果想自定义配置信息,怎么办?可以自定义配置类 SwaggerConfig,也可以写在配置文件里,如下:

application.yml 代码

server:port: 1001eureka:instance:hostname: 127.0.0.1client:serviceUrl:defaultZone: http://${eureka.instance.hostname}:8080/eureka/spring:application:name: product-server# swagger 相关配置
swagger:title: "无限商城-产品模块"description: "让天下没有难写的代码"version: V1.0enabled: true

然后到网关服务的代码

pom.xml 配置

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><parent><artifactId>swagger-gateway</artifactId><groupId>com.study</groupId><version>1.0-SNAPSHOT</version></parent><modelVersion>4.0.0</modelVersion><artifactId>gateway-server</artifactId><dependencies><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-gateway</artifactId></dependency></dependencies></project>

配置类 SwaggerConfig,需要实现接口:springfox.documentation.swagger.web.SwaggerResourcesProvider

package com.study.config;import lombok.AllArgsConstructor;
import org.springframework.cloud.gateway.config.GatewayProperties;
import org.springframework.cloud.gateway.route.RouteLocator;
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;/*** @author biandan* @description* @signature 让天下没有难写的代码* @create 2021-06-07 上午 1:29*/
@Component
@Primary
@AllArgsConstructor
public class SwaggerConfig implements SwaggerResourcesProvider {public static final String API_URI = "/v2/api-docs";private final RouteLocator routeLocator;private final GatewayProperties gatewayProperties;@Overridepublic List<SwaggerResource> get() {List<SwaggerResource> resources = new ArrayList<>();List<String> routes = new ArrayList<>();//取出gateway的routerouteLocator.getRoutes().subscribe(route -> routes.add(route.getId()));//结合配置的route-路径(Path),和route过滤,只获取有效的route节点gatewayProperties.getRoutes().stream().filter(routeDefinition -> routes.contains(routeDefinition.getId())).forEach(routeDefinition -> routeDefinition.getPredicates().stream().filter(predicateDefinition -> ("Path").equalsIgnoreCase(predicateDefinition.getName())).forEach(predicateDefinition -> resources.add(swaggerResource(routeDefinition.getId(),"/"+routeDefinition.getId()+API_URI ))));return resources;}private SwaggerResource swaggerResource(String name, String location) {SwaggerResource swaggerResource = new SwaggerResource();swaggerResource.setName(name);swaggerResource.setLocation(location);swaggerResource.setSwaggerVersion("2.0");return swaggerResource;}}

控制层 controller

package com.study.controller;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
import springfox.documentation.swagger.web.*;import java.util.Optional;/*** @author biandan* @description* @signature 让天下没有难写的代码* @create 2021-06-07 上午 1:31*/
@RestController
@RequestMapping("/swagger-resources")
public class SwaggerController {@Autowired(required = false)private SecurityConfiguration securityConfiguration;@Autowired(required = false)private UiConfiguration uiConfiguration;private final SwaggerResourcesProvider swaggerResources;@Autowiredpublic SwaggerController(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));}@GetMapping("")public Mono<ResponseEntity> swaggerResources() {return Mono.just((new ResponseEntity<>(swaggerResources.get(), HttpStatus.OK)));}
}

重点来了,application.yml 配置

server:port: 80eureka:instance:hostname: 127.0.0.1client:serviceUrl:defaultZone: http://${eureka.instance.hostname}:8080/eureka/spring:application:name: gateway-servercloud:gateway:discovery:locator:enabled: true  #表明gateway开启服务注册和发现的功能, 动态路由lowerCaseServiceId: trueroutes:# 路由的 ID,没有固定规则但要求唯一,建议配合服务名# 产品微服务路由- id: product-server# 根据服务名称从注册中心获取服务地址uri: lb://product-server# 断言predicates:- Path=/**# 产品微服务路由- id: order-server# 根据服务名称从注册中心获取服务地址uri: lb://order-server# 断言predicates:- Path=/**

说明:

1、配置动态路由,否则会报错:Failed to load API definition. 找不到 API 的定义

2、为每个微服务配置路由规则 routes,否则报错: 

系列学习 Swagger 之第 2 篇 —— SpringCloud Gateway 整合 Swagger(完结)相关推荐

  1. springcloud gateway 整合swagger3.0.0

    版本和说明 swagger:3.0.0 gateway微服务的使用方式和单应用没啥区别,只是多了设置右上角模块的操作. 以下操作基于你已经搭建成功的服务,只讲怎么添加swagger3 单应用 pom添 ...

  2. SpringCloud系列教程(五)之SpringCloud Gateway 网关聚合开发文档 swagger knife4j 和登录权限统一验证【Hoxton版】

    阅读提醒: 本文面向的是有一定springboot基础者 本次教程使用的Spring Cloud Hoxton RELEASE版本 由于knife4j比swagger更加友好,所以本文集成knife4 ...

  3. Java微服务——SpringCloud实战篇2:整合Gateway、Config、Bus

    Java微服务--SpringCloud实战篇2:整合Gateway.Config.Bus 如果小伙伴在阅读下列内容时,对于编写SpringCloud项目是零基础,那么请先阅读小编的另一篇博文:&qu ...

  4. springcloud gateway 使用nacos 动态过滤器 记一次线上网关升级cpu升高的问题

    大家好,我是烤鸭: ​ 网关升级,想使用 springcloud gateway nacos 动态过滤器配置(原来是硬编码的方式),升级之后出了一些问题(cpu升高,ygc频繁),记录一下. 关于 s ...

  5. SpringCloud gateway (史上最全)

    前言 疯狂创客圈(笔者尼恩创建的高并发研习社群)Springcloud 高并发系列文章,将为大家介绍三个版本的 高并发秒杀: 一.版本1 :springcloud + zookeeper 秒杀 二.版 ...

  6. 微服务网关:SpringCloud Gateway保姆级入门教程

    什么是微服务网关 SpringCloud Gateway是Spring全家桶中一个比较新的项目,Spring社区是这么介绍它的: 该项目借助Spring WebFlux的能力,打造了一个API网关.旨 ...

  7. SpringCloud Gateway 详解

    文章目录 一.网关简介 1.服务网关介绍 1.1 API网关介绍 1.2 网关主要功能 2.常用网关介绍 2.1 Nginx+Lua 2.2 Kong 2.3 Traefik 2.4 Zuul 二.S ...

  8. 什么是微服务网关?SpringCloud Gateway保姆级入门教程

    什么是微服务网关 SpringCloud Gateway是Spring全家桶中一个比较新的项目,Spring社区是这么介绍它的: 该项目借助Spring WebFlux的能力,打造了一个API网关.旨 ...

  9. 六、SpringSecurity OAuth2 + SpringCloud Gateway实现统一鉴权管理

    代码 代码仓库:地址 代码分支:lesson6 博客:地址 简介 在先前文章中,我们使用SpringSecurity OAuth2搭建了一套基于OAuth2协议的授权系统,并扩展了手机验证码授权模式. ...

  10. springcloud gateway结合knife4j生成Api文档

    springcloud gateway结合knife4j生成Api文档 学习中笔记 一. 接口模块(mxm-system-api)引入依赖 <dependency><groupId& ...

最新文章

  1. cephfs linux kernel client针对superblock操作流程的分析
  2. Win32 鼠标绘图代码研究
  3. 默认构造函数和拷贝构造函数
  4. python collections,函数等笔记
  5. phpmyadmin出现缺少mysqli扩展问题
  6. 服务器位置不可用,服务器的MSDTC不可用解决办法
  7. 虚幻4 游戏引擎(一):材质教学
  8. 数据库课设 - 机票预订系统
  9. 001_KNN与线性分类器
  10. 树莓派Python3 使用定时器
  11. 20以内的加减法辅导
  12. java 读取hdfs上的文件内容
  13. 全球最强人工智能创新公司Top100榜单重磅发布!
  14. BDC的执行模式与更新模式
  15. git pull报错Pulling is not possible because you have unmerged files
  16. 将实时三维计算机技术,基于结构光实时三维重建计算机应用技术专业论文.docx...
  17. apt-get --allow-unauthenticated upgrade
  18. 把思科端口速率改为不协商_端口汇聚—TRUNK技术介绍
  19. 程旭:CPU方寸上的中国信念
  20. 我的QQ终于能传文件了

热门文章

  1. 微分方程建模——以传染病模型为例
  2. android信鸽推送通知栏,【信鸽推送】点击推送通知后,默认会从程序Launcher进入,返回时会回到主界面的问题...
  3. java 148. 排序链表
  4. jvm之java类加载机制和类加载器(ClassLoader)的详解
  5. excel 姓名汉字转拼音
  6. android re浏览器下载,re浏览器官方版下载_re浏览器app下载4.9.6 - 系统城
  7. 链家上海2018年9月二手房
  8. 查看数据库实例名的方法:
  9. Unity Behavior Designer(行为树)Abort Type(中断类型)
  10. 服务器虚拟网卡驱动卸载,Win10安装和卸载万能网卡版驱动的方法