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

本文详细介绍如何在SpringCloud Gateway中整合Swagger组件,实现服务网关对多个微服务API文档的聚合显示。涵盖SpringBoot、SpringCloud、Swagger的版本配置,以及自定义配置类、过滤器的编写,确保网关与Swagger的兼容性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 父项目
    Eureka 15002 注册中心
    Gateway 15000 网关
    Comment 15003 应用服务
  • 项目树

    一个注册中心
    一个网关
    一个应用服务
    |_ 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())//
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值