莫大人

3、nacos+springcloudgateway+knife4j集成

knife4j官方文档 nacos springcloud gateway聚合OpenApi

 

https://doc.xiaominfo.com/knife4j/action/aggregation-cloud.html

 

knife4j

背景

虽然swagger已经提供了UI解决方案,但存在2点不如意的地方。

1、无法搜索相关接口;在接口文档多起来之后,想要找到一个接口很困难。

2、swagger的UI以及排版真的丑。

解决方案

有没有解决方案呢,有。knife4j官方文档 目前提供了springboot版本和微服务版本的接口聚合解决方案。

nacos+springcloud-gateway+knife4j集成步骤

微服务端

  • 添加依赖knife4j-micro-spring-boot-starter

  • 添加nacos配置

网关端

  • 添加依赖knife4j-spring-boot-starter

  • 添加nacos配置

  • 添加聚合配置

声明版本

<properties>
<guo.version>0.0.1-SNAPSHOT</guo.version>
<spring-boot.version>2.3.2.RELEASE</spring-boot.version>
<spring-cloud.version>Hoxton.SR8</spring-cloud.version>
<spring-cloud.alibaba>2.2.5.RELEASE</spring-cloud.alibaba>

<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<lombok.version>1.18.12</lombok.version>

<swagger.fox.version>3.0.0</swagger.fox.version>
<knife4j.version>2.0.8</knife4j.version>
<spring-boot-admin.version>2.4.1</spring-boot-admin.version>

<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>

</properties>

<!-- Swagger 增强knife4j UI资源与微服务starter -->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>${knife4j.version}</version>
<scope>compile</scope>
</dependency>
<!-- Swagger 增强knife4j 微服务starter -->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-micro-spring-boot-starter</artifactId>
<version>${knife4j.version}</version>
<scope>compile</scope>
</dependency>

 

微服务端

添加依赖knife4j-micro-spring-boot-starter

<!-- Swagger -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
</dependency>
<!-- Swagger 增强knife4j 微服务starter -->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-micro-spring-boot-starter</artifactId>
</dependency>

添加swagger配置-选配

package com.guo.user.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;

import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2WebMvc
@Import(BeanValidatorPluginsConfiguration.class)
public class SwaggerConfig {

/**
* 创建RestApi 并包扫描controller
*
* @return
*/
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select()
// 指定目录生成API
.apis(RequestHandlerSelectors.basePackage("com.guo.user.controller"))
// 对所有api进行监控
//               .apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any()).build();
}

/**
* 创建Swagger页面 信息
*
* @return
*/
private ApiInfo apiInfo() {
return new ApiInfoBuilder().title("消费者服务").description("springfox-swagger 3.0.0接口文档用法演示描述")
.termsOfServiceUrl("http://www.baidu.com/").version("1.0").build();

}

}

启动访问swagger服务是否成功

http://localhost:9203/swagger-ui/index.html

 

添加nacos配置

#==============================knife4j配置=======================================
knife4j:
# 开启增强配置
enable: true
# 是否生产环境 默认否;生产环境配置为true,将无法访问文档
production: false
basic:
  enable: true
  # Basic认证用户名
  username: product
  # Basic认证密码
  password: 111111

 

网关端

添加依赖knife4j-spring-boot-starter

        <dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
</dependency>

 

添加nacos配置

spring:
cloud:
  gateway:
    routes:
      # 用户模块
      - id: guo-feign-user
        uri: lb://guo-feign-user
        predicates:
          - Path=/user/**
        filters:
          - StripPrefix=1
      # 账户模块
      - id: guo-feign-account
        uri: lb://guo-feign-account
        predicates:
          - Path=/account/**
        filters:
          - StripPrefix=1
      # 产品模块
      - id: guo-feign-product
        uri: lb://guo-feign-product
        predicates:
          - Path=/product/**
        filters:
          - StripPrefix=1

 

添加聚合配置

package com.guo.gateway.config.swagger;

import java.util.ArrayList;
import java.util.List;

import org.springframework.cloud.gateway.config.GatewayProperties;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.support.NameUtils;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

import lombok.AllArgsConstructor;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;

@Component
@Primary
@AllArgsConstructor
public class SwaggerProvider implements SwaggerResourcesProvider {

  private final RouteLocator routeLocator;
  private final GatewayProperties gatewayProperties;


  @Override
  public List<SwaggerResource> get() {
      List<SwaggerResource> resources = new ArrayList<>();
      List<String> routes = new ArrayList<>();
      routeLocator.getRoutes().subscribe(route -> routes.add(route.getId()));
      gatewayProperties.getRoutes().stream().filter(routeDefinition -> routes.contains(routeDefinition.getId()))
      .forEach(route -> route.getPredicates().stream()
                  .filter(predicateDefinition -> ("Path").equalsIgnoreCase(predicateDefinition.getName()))
                  .forEach(predicateDefinition -> resources.add(swaggerResource(route.getId(),
                          predicateDefinition.getArgs().get(NameUtils.GENERATED_NAME_PREFIX + "0")
                                  .replace("**", "v2/api-docs"))))
      );

      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;
  }
}

 

package com.guo.gateway.config.swagger;

import java.util.Optional;

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.SecurityConfiguration;
import springfox.documentation.swagger.web.SecurityConfigurationBuilder;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;
import springfox.documentation.swagger.web.UiConfiguration;
import springfox.documentation.swagger.web.UiConfigurationBuilder;

@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));
  }

  @SuppressWarnings("rawtypes")
  @GetMapping("")
  public Mono<ResponseEntity> swaggerResources()
  {
      return Mono.just((new ResponseEntity<>(swaggerResources.get(), HttpStatus.OK)));
  }
}

关于授权

  • 通过授权接口获取token

  • 在swagger或knife4j上添加全局参数,后续访问接口都会携带这些参数

代码地址

demo

 

posted on 2021-07-02 17:57  莫大人  阅读(3195)  评论(0编辑  收藏  举报

导航