Loading [MathJax]/jax/output/CommonHTML/config.js
首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >Spring Cloud 之服务网关 Gateway(二) 集成 Swagger 组件

Spring Cloud 之服务网关 Gateway(二) 集成 Swagger 组件

作者头像
芥末鱿鱼
发布于 2020-09-22 02:32:32
发布于 2020-09-22 02:32:32
2.1K0
举报
文章被收录于专栏:玩转 Spring Cloud玩转 Spring Cloud

Spring Cloud 之服务网关 Gateway(二) 集成 Swagger 组件

概述

Swagger 是一个可视化 API 测试工具, 能够有效的构建强大的 Restful API 文档, 省去接口文档管理工作. 如果修改了代码, API 文档也会实时更新. 并且可以部分替代 Postman 用来调试接口

Spring Boot 整合了 swagger 组件, 使用也比较简单. 微服务随着项目的增加, 访问每一个应用的 swagger 显然是不合适的. 我们希望网关可以将所有的应用的 swagger 页面聚合起来. 这样前端只要访问网关的 swagger 的就可以了

Spring Cloud Gateway 整合 Swagger 会有一个麻烦, Gateway 底层是 WebFlux, 而 WebFlux 和 Swagger 不兼容. 所以不能通过一般的 Spring Boot 项目的方式简单的整合 Swagger, 否则启动的时候会报错. 常用的做法是自定义几个配置类来实现

编写简单案例

聚合模块说明

  • 版本说明 Spring Boot : 2.0.9.RELEASE Spring Cloud: Finchley.RELEASE
  • 项目整体结构采用 maven 多 Module 结构 模块端口说明Demo父项目Eureka15002注册中心Gateway15000网关Comment15003应用服务
  • 项目树 一个注册中心 一个网关 一个应用服务 |_ demo |_ eureka |_ gateway |_ comment |_ pom.xml

编写 Eureka 服务

参考: Spring Cloud 之 Eureka 服务注册与发现

配置信息

编写应用程序服务 Comment-server

  • 编写 pom 文件 <dependencies> <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-web</artifactId> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency> </dependencies>
  • 编写工程的配置文件, eureka: client: service-url: defaultZone: http://localhost:15002/eureka/ instance: lease-renewal-interval-in-seconds: 5 lease-expiration-duration-in-seconds: 15 perfer-in-address: true server: port: 15003 spring: application: name: comment-server profiles: active: dev
  • 编写配置类 @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket createRestApi(){ return new Docket(DocumentationType.SWAGGER_2)// .apiInfo(apiInfo())// .select()// .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))// .paths(PathSelectors.any())// .build(); } private ApiInfo apiInfo(){ return new ApiInfoBuilder()// .title("Swagger API")// .description("test")// .termsOfServiceUrl("")// .contact(new Contact("Spring Cloud China","http://springcloud.cn",""))// .version("2.0")// .build(); } }
  • 编写控制器 @RestController @RequestMapping("/comments") @Slf4j @Api("comments") public class CommentController { @Autowired private CommentService commentService; @ApiOperation(value = "获取评论详情", notes = "根据评论 id 获取详情") @ApiParam(value = "评论id") @GetMapping("/detail/{id}") public String getCommentDetails(@PathVariable("id") String id) { log.debug("Get comment by id [{}]", id); return id; } }
  • 验证效果 服务启动后, 通过访问 http://localhost:15003/swagger-ui.html 访问 API 文档界面

编写 Gateway 网关服务

  • 编写 pom 文件 <dependencies> <!-- 健康监控 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <!-- Spring Cloud Gateway 依赖 --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <!-- swagger --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> </dependencies>
  • application.yml 文件配置 spring: application: name: gateway cloud: gateway: discovery: locator: enabled: true # 开启基于服务发现的路由规则 lower-case-service-id: true # 开启小写的 serviceId 进行基于服务路由的转发 routes: - id: comment_server_route uri: lb://comment-server # 路由集群内其他服务,url需要用[lb://]+[serviceId] predicates: - Path=/comment/** filters: - SwaggerHeaderFilter - StripPrefix=1 loadbalancer: retry: enabled: true # 内部已默认开启负载均衡 eureka: client: service-url: defaultZone: http://localhost:15002/eureka/ # 指定注册中心地址, 以便使用服务发现功能 instance: lease-renewal-interval-in-seconds: 5 lease-expiration-duration-in-seconds: 15 perfer-in-address: true server: port: 15000 management: endpoints: health: enabled: true gateway: enabled: true web: exposure: include: "*" # 暴露所有端点, 默认是 info, health logging: level: org.springframework.cloud.gateway: debug
  • 配置 GatewaySwaggerProvider, 获取 Api-doc, 即 GatewaySwaggerProvider @Component @Primary public class GatewaySwaggerProvider implements SwaggerResourcesProvider { public static final String API_URI = "/v2/api-docs"; private final RouteLocator routeLocator; private final GatewayProperties gatewayProperties; public GatewaySwaggerProvider(RouteLocator routeLocator, GatewayProperties gatewayProperties) { this.routeLocator = routeLocator; this.gatewayProperties = gatewayProperties; } @Override public List<SwaggerResource> get() { List<SwaggerResource> resources = new ArrayList<>(); List<String> routes = new ArrayList<>(); // 取出 Spring Cloud Gateway 中的 route routeLocator.getRoutes()// .subscribe(route -> routes.add(route.getId())); // 结合 application.yml 中的路由配置, 只获取有效的 route 节点 gatewayProperties.getRoutes().stream()// .filter(routeDefinition -> routes.contains(routeDefinition.getId()))// .forEach(routeDefinition -> routeDefinition.getPredicates().stream()// .filter(predicateDefinition -> "Path".equalsIgnoreCase(predicateDefinition.getName().toLowerCase()))// .forEach(predicateDefinition -> resources.add(swaggerResource(routeDefinition.getId(), predicateDefinition.getArgs()// .get(NameUtils.GENERATED_NAME_PREFIX + "0")// .replace("/**", 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; } }
  • 编写 swagger-resource 端点 @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)); } @GetMapping("") public Mono<ResponseEntity> swaggerResources() { return Mono.just((new ResponseEntity<>(swaggerResources.get(), HttpStatus.OK))); } }
  • 配置过滤器 (**Finchley.SR2 版本可跳过这一步, 配置文件里的 - SwaggerHeaderFilter 也不用配置 **) @Component public class SwaggerHeaderFilter extends AbstractGatewayFilterFactory { private static final String HEADER_NAME = "X-Forwarded-Prefix"; @Override public GatewayFilter apply(Object config) { return (exchange, chain) -> { ServerHttpRequest request = exchange.getRequest(); String path = request.getURI().getPath(); if(!StringUtils.endsWithIgnoreCase(path, GatewaySwaggerProvider.API_URI)){ return chain.filter(exchange); } String basePath = path.substring(0,path.lastIndexOf(GatewaySwaggerProvider.API_URI)); ServerHttpRequest newRequest = request.mutate().header(HEADER_NAME,basePath).build(); ServerWebExchange newExchange = exchange.mutate().request(newRequest).build(); return chain.filter(newExchange); }; } }
  • 启动类 @SpringBootApplication public class GatewayApplication { public static void main(String[] args) { SpringApplication.run(GatewayApplication.class, args); } }

发送请求测试效果

注册中心(eureka), 网关服务(gateway) 和应用服务(comment-server)依次启动后, 访问 http://localhost:15000/swagger-ui.html 可以看到 swagger 页面

我的博客即将搬运同步至腾讯云+社区,邀请大家一同入驻:https://cloud.tencent.com/developer/support-plan

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020/09/16 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
spring cloud gateway聚合swagger的方法记录
最近在使用spring cloud gateway,需要对各个微服务做一个聚合的swagger功能。 其实方法也是上网找的,不过也记录一下:
星痕
2019/07/04
3.7K0
【Knife4j】小试牛刀,基于gateway的集成
均参考上篇文章即可,可回头看《【Knife4j】小试牛刀,基于eureka的集成》
小尘哥
2022/09/01
1.4K0
【Knife4j】小试牛刀,基于gateway的集成
SpringCloud Alibaba 实战教程13-gateway网关聚合swagger
一、项目整合整合swagger 1.1引入pom文件 <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <ve
gang_luo
2021/02/22
1.8K0
SpringCloud Alibaba 实战教程13-gateway网关聚合swagger
springcloud:gateway网关聚合swagger实现多个服务接口切换
springcloud是由多个不同的springboot服务组成的,微服务使用swagger有两种方法,如下:
Freedom123
2024/03/29
1.2K0
springcloud:gateway网关聚合swagger实现多个服务接口切换
集成SWAGGER2服务-spring cloud 入门教程
Swagger 是最流行的用于设计、构建和记录 RESTful API 的工具。它与 Spring Boot 有很好的集成。要将其与 Spring 结合使用,我们需要向 Maven管理文件中 添加以下两个依赖项pom.xml。
jack.yang
2025/04/05
2600
集成SWAGGER2服务-spring cloud 入门教程
Spring Cloud Gateway 聚合swagger文档
关于pigX:全网最新的微服务脚手架,Spring Cloud Finchley、oAuth2的最佳实践
冷冷
2018/07/20
2.4K0
SpringCloud-gateway-nacos-swagger踩坑记录
​ 在gateway中集成各个模块,然后接入swagger方便测试各模块接口,其中sunshine-common是放入一些通用组件和配置的,swagger的配置就在这里面。sunshine-gateway即网关模块,在网关通过nacos服务注册发现,将请求路由到各个模块中。
doper
2022/09/26
1.7K0
SpringCloud-gateway-nacos-swagger踩坑记录
Spring Boot: SpringFox Swagger原理解析及简单实用
API的全称是应用编程接口(Application Programming Interface) 在互联网时代,把网站的服务封装成一系列计算机易识别的数据接口开放出去,供第三方开发者使用,这种行为就叫做开放网站的API,与之对应的,所开放的API就被称作Open API。
Freedom123
2024/03/29
1K0
Spring Boot: SpringFox Swagger原理解析及简单实用
微服务聚合Swagger文档,这波操作是真的香!
对比knife4j和原生Swagger的微服务使用,再次证明knife4j是springfox-swagger的增强UI实现,完全遵循了springfox-swagger中的使用方式。
macrozheng
2020/07/24
4.8K0
微服务聚合Swagger文档,这波操作是真的香!
Nacos + Spring Cloud Gateway动态路由配置
具体的Nacos怎么配置就不介绍了,可以参考阿里巴巴的官方介绍,这里通过windows直接本地启动开启单机模式,登录Nacos Console,创建dev的namespace,在dev下的默认分组下创建gateway-router的dataId
BUG弄潮儿
2021/06/25
7.5K0
Nacos + Spring Cloud Gateway动态路由配置
Spring Cloud Gateway解析
Gateway( 网关),顾名思义,是出现在系统边界上的一个面向API或应用服务的、串行集中式的强管控服务,这里我们讨论的边界可以基于企业IT系统的边界,当然,可以理解为企业级应用防火墙,其目标主要起到隔离外部访问与内部系统交互的作用。在微服务概念的流行之前,网关就已经诞生了,在面向SOA体系中已经成熟,然而,随着微服务体系的快速发展,更进一步将Gateway推向更高的浪口。与其说网关催生了微服务体系,不如说微服务体系拥抱了网关。
Luga Lee
2021/12/09
9920
Spring Cloud Gateway解析
聊聊spring cloud gateway的RouteLocator
本文主要研究一下spring cloud gateway的RouteLocator
code4it
2018/09/17
3K0
集成 Kubernetes 来构建微服务-spring cloud 入门教程
Spring Cloud和Kubernetes是目前Java平台下微服务应用的使用得最多的产品。然而,当谈到微服务架构时,它们有时被描述为具有竞争力的解决方案。它们都在微服务架构中实现流行的模式,如服务发现、分布式配置、负载平衡或断路。当然,他们的做法不同。 Kubernetes 是一个用于运行、扩展和管理容器化应用程序的平台。Kubernetes 最重要的组件之一是etcd。该高度可用的键值存储负责存储所有集群数据,包括服务注册表和应用程序配置。我们不能用任何其他工具代替它。可以使用Istio或 Linkerd等第三方组件来实现更高级的路由和负载均衡策略。要在 Kubernetes 上部署和运行应用程序,我们无需在源代码中添加任何内容。编排和配置是在应用程序之外实现的——在平台上。 Spring Cloud 提出了一种不同的方法。所有组件都必须在应用程序端包含和配置。它为我们提供了许多与用于云原生开发的各种工具和框架集成的可能性。但是,一开始 Spring Cloud 是围绕 Eureka、Ribbon等 Netflix OSS 组件构建的、Hystrix 或 Zuul。它为我们提供了一种机制,可以轻松地将它们包含到我们基于微服务的架构中,并将它们与其他云原生组件集成。一段时间后,必须重新考虑这种方法。今天,我们有很多由 Spring Cloud 开发的组件,比如 Spring Cloud Gateway(Zuul 替代品)、Spring Cloud Load Balancer(Ribbon 替代品)、Spring Cloud Circuit Breaker(Hystrix 替代品)。还有一个相对较新的与Kubernetes集成的项目——Spring Cloud Kubernetes。
jack.yang
2025/04/05
3290
集成 Kubernetes 来构建微服务-spring cloud 入门教程
Spring Cloud Gateway 服务网关的部署与使用详细教程
点击上方“芋道源码”,选择“设为星标” 管她前浪,还是后浪? 能浪的浪,才是好浪! 每天 10:33 更新文章,每天掉亿点点头发... 源码精品专栏 原创 | Java 2021 超神之路,很肝~ 中文详细注释的开源项目 RPC 框架 Dubbo 源码解析 网络应用框架 Netty 源码解析 消息中间件 RocketMQ 源码解析 数据库中间件 Sharding-JDBC 和 MyCAT 源码解析 作业调度中间件 Elastic-Job 源码解析 分布式事务中间件 TCC-Transaction
芋道源码
2022/10/09
5.5K0
Spring Cloud Gateway 服务网关的部署与使用详细教程
自研网关:多项目的swagger聚合功能
网关一般都会有一个swagger聚合功能,方便于你测试文档接口。 但网上的例子,如https://doc.xiaominfo.com/solution/ui-front-gateway.html#%E6%96%87%E6%A1%A3%E8%81%9A%E5%90%88%E4%B8%9A%E5%8A%A1%E7%BC%96%E7%A0%81. 这些例子都能解决swagger聚合的问题,但问题是他只支持一个项目,但我网关肯定会有多个项目,这个怎么处理呢。 其实这个原理一样,但说起来也是有几个技术难点的.
星痕
2020/09/15
1.4K0
SpringBoot集成Swagger
bootstrap-ui 访问 http://localhost:8081/doc.html
shaoshaossm
2022/12/27
3700
SpringBoot集成Swagger
Spring项目如何集成Gateway和Nacos服务
在本文中,我们将探讨如何在Spring项目中集成Gateway和Nacos服务,帮助初学者成功地完成这些存在解决方案。通过本文,您将了解完整的集成流程和具体实现方法,以提高项目性能和拓展性。
默 语
2025/01/20
5640
使用 Spring Boot 2.0,Eureka 和 Spring Cloud 的微服务快速指南
原文地址:https://dzone.com/articles/quick-guide-to-microservices-with-spring-boot-20-e
Techeek
2018/06/29
7.9K0
使用 Spring Boot 2.0,Eureka 和 Spring Cloud 的微服务快速指南
SPRING CLOUD 微服务快速指南-spring cloud 入门教程
我的博客上有很多关于使用 Spring Boot 和 Spring Cloud 进行微服务的文章。本文的主要目的是简要总结这些框架提供的最重要的组件,这些组件可以帮助您创建微服务,并实际上向您解释什么是用于微服务架构的 Spring Cloud。本文涵盖的主题是:
jack.yang
2025/04/05
6750
SPRING CLOUD 微服务快速指南-spring cloud 入门教程
Spring Boot:整合Swagger文档
spring-boot作为当前最为流行的Java web开发脚手架,越来越多的开发者选择用其来构建企业级的RESTFul API接口。这些接口不但会服务于传统的web端(b/s),也会服务于移动端。在实际开发过程中,这些接口还要提供给开发测试进行相关的白盒测试,那么势必存在如何在多人协作中共享和及时更新API开发接口文档的问题。 
朝雨忆轻尘
2019/06/19
1.1K0
Spring Boot:整合Swagger文档
相关推荐
spring cloud gateway聚合swagger的方法记录
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
首页
学习
活动
专区
圈层
工具
MCP广场
首页
学习
活动
专区
圈层
工具
MCP广场