Spring Cloud Zuul 整合 Swagger

1.概述

网关作为API文档的统一入口,网关聚合所有微服务的文档,通过在网关进行切换来实现对其他服务API文档的访问。本篇将介绍如何在以Spring Cloud Zuul作为网关的微服务中集成Swagger文档。

2.搭建服务

这里以 student-servic e和 teacher-service 两个微服务为例

  • 添加依赖

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        <version>2.2.0.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>com.github.xiaoymin</groupId>
        <artifactId>knife4j-micro-spring-boot-starter</artifactId>
        <version>3.0.1</version>
    </dependency>
    
  • 添加配置

    server:
      port: 8001
      servlet:
        context-path: /
    
    spring:
      application:
        name: student-service
      profiles:
        active: dev
    
    eureka:
      instance:
        instance-id: student-service-8001
        prefer-ip-address: true
      client:
        register-with-eureka: true
        fetch-registry: true
        service-url:
          defaultZone: http://localhost:8000/eureka
    
  • 添加Swagger配置类

    @Configuration
    @EnableSwagger2
    @EnableKnife4j
    @PropertySource("classpath:/application.yml")
    @Import(BeanValidatorPluginsConfiguration.class)
    public class SwaggerConfig {
    
        /**
         * 获取当前SpringBoot运行环境
         */
        @Value("${spring.profiles.active}")
        private String env;
    
        @Bean
        public Docket docket(){
            Docket docket = new Docket(DocumentationType.SWAGGER_2);
            // 设置在开发环境中启用
            if(this.env.equals("dev")){
                docket.enable(true);
            }else {
                docket.enable(false);
            }
    
            // 设置信息
            docket.apiInfo(apiInfo());
    
            // 扫描接口
            docket.select()
                .apis(RequestHandlerSelectors.basePackage("com.controller"))
                .build();
            docket.select()
                .paths(PathSelectors.any())
                .build();
    
            return docket;
        }
    
        /**
         * 文档基础信息
         * @return
         */
        public ApiInfo apiInfo(){
            Contact contact = new Contact("xxx", "xxx", "xxx");
            ApiInfo apiInfo = new ApiInfo(
                    "Student微服务的Swagger文档",
                    "这是Student微服务项目的接口文档",
                    "v1.0",
                    "xxx",
                    contact,
                    "Apache 2.0",
                    "http://www.apache.org/licenses/LICENSE-2.0",
                    new ArrayList()
            );
    
            return apiInfo;
        }
    }
    
  • 添加Controller控制器

    @RestController
    @RequestMapping("/student")
    @Api(tags = "StudentController", description = "学生控制器")
    public class StudentController {
    
        @GetMapping("/show")
        @ApiOperation("展示用户")
        public List<Student> showStudents(){
            List<Student> students = new ArrayList<>();
            Student student1 = new Student(1L, "张三", "男");
            Student student2 = new Student(2L, "李四", "男");
            Student student3 = new Student(3L, "王五", "女");
    
            students.add(student1);
            students.add(student2);
            students.add(student3);
    
            return students;
        }
    }
    

2.搭建网关

  • 添加依赖

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        <version>2.2.0.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
        <version>2.2.0.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>com.github.xiaoymin</groupId>
        <artifactId>knife4j-spring-boot-starter</artifactId>
        <version>3.0.1</version>
    </dependency>
    
  • 添加配置

    server:
      port: 8080
      servlet:
        context-path: /
    
    spring:
      application:
        name: eureka-zuul
    
    eureka:
      instance:
        instance-id: eureka-zuul-8080
        prefer-ip-address: true
      client:
        register-with-eureka: true
        fetch-registry: true
        service-url:
          defaultZone: http://localhost:8000/eureka
    
    zuul:
      routes:
        student-service:
          path: /student-service/**
        teacher-service:
          path: /teacher-service/**
          
    management:
      endpoints:
        web:
          exposure:
            include: '*'
    
  • 添加Swagger配置类

    @Component
    @Primary
    public class SwaggerConfig implements SwaggerResourcesProvider {
    
        @Autowired
        RouteLocator routeLocator;
    
        @Override
        public List<SwaggerResource> get() {
            List<SwaggerResource> resources = new ArrayList<>();
            List<Route> routes = routeLocator.getRoutes();
    
            // 获取所有路由信息
            for (Route route : routes) {
                resources.add(swaggerResource(route.getId(), route.getFullPath()
                                              .replace("**", "v2/api-docs")));
            }
    
            return resources;
        }
    
        private SwaggerResource swaggerResource(String name, String location) {
            System.out.printf("name:%s, location:%s\n", name, location);
    
            SwaggerResource swaggerResource = new SwaggerResource();
            swaggerResource.setName(name);
            swaggerResource.setLocation(location);
            swaggerResource.setSwaggerVersion("2.0");
            return swaggerResource;
        }
    }
    
  • 添加Controller控制器

    @RestController
    public class SwaggerController {
    
        @Autowired(required = false)
        private SecurityConfiguration securityConfiguration;
    
        @Autowired(required = false)
        private UiConfiguration uiConfiguration;
    
        private final SwaggerResourcesProvider swaggerResources;
    
        @Autowired
        public SwaggerController(SwaggerResourcesProvider swaggerResources) {
            this.swaggerResources = swaggerResources;
        }
    
        /**
         * Swagger安全配置,支持oauth和apiKey设置
         */
        @GetMapping("/swagger-resources/configuration/security")
        public Mono<ResponseEntity<SecurityConfiguration>> securityConfiguration() {
            return Mono.just(
                new ResponseEntity<>(
                    Optional.ofNullable(securityConfiguration).orElse(
                        SecurityConfigurationBuilder.builder().build()),HttpStatus.OK));
        }
    
        /**
         * Swagger UI配置
         */
        @GetMapping("/swagger-resources/configuration/ui")
        public Mono<ResponseEntity<UiConfiguration>> uiConfiguration() {
            return Mono.just(new ResponseEntity<>(
                    Optional.ofNullable(uiConfiguration).orElse(
                        UiConfigurationBuilder.builder().build()), HttpStatus.OK));
        }
    
        /**
         * Swagger资源配置,微服务中这各个服务的api-docs信息
         */
        @GetMapping("/swagger-resources")
        public Mono<ResponseEntity> swaggerResources() {
            return Mono.just((new ResponseEntity<>(
                swaggerResources.get(), HttpStatus.OK)));
        }
    }
    

4.测试访问

访问地址:http://localhost:8080/student-service/v2/api-docs

在这里插入图片描述

访问地址:http://localhost:8080/swagger-resources

在这里插入图片描述

访问地址:http://localhost:8080/doc.html

在这里插入图片描述

在这里插入图片描述


【源码地址】:GitHub

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

编程小吉

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值