swagger增强knife4j在gateway中的使用入门

knife4j在gateway中的使用入门


文章目录


1. 简介

knife4j 是对swagger的增强。

1.1 pom

<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>knife4j-spring-boot-starter</artifactId>
    <version>3.0.2</version>
</dependency>

2. gateway集成

2.1 gateway 网关模块

  1. 添加 knife4j pom
  2. 添加配置类,从网关获取 服务列表
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
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 springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;

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

@Slf4j
@Component
@Primary
@AllArgsConstructor
public class SwaggerResourceConfig implements SwaggerResourcesProvider {

                    
    /**
     * 版本号,建议v2, v3版本有bug,网关界面获取不到 baseUrl
     */              
    public static final String SWAGGER_V2_URL = "v2/api-docs";
    private final RouteLocator routeLocator;
    private final GatewayProperties gatewayProperties;


   /**
     * 从 网关获取 所有的微服务,服务名称重复的排除
     * @return
     */
    @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("**", SWAGGER_V2_URL))));
        });
        return resources;
    }

    private SwaggerResource swaggerResource(String name, String location) {
        log.info("name:{},location:{}", name, location);
        SwaggerResource swaggerResource = new SwaggerResource();
        swaggerResource.setName(name);
        swaggerResource.setLocation(location);
        swaggerResource.setSwaggerVersion("2.0");
        return swaggerResource;
    }
}
  1. 添加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.RestController;
import reactor.core.publisher.Mono;
import springfox.documentation.swagger.web.*;

import java.util.Optional;

@RestController("/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)));
    }
}

2.2 微服务模块

  1. 新增kenfe4j 项目
<?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>wx-common</artifactId>
        <groupId>com.wx</groupId>
        <version>1.0</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>wx-common-knife4j</artifactId>

    <description>
        wx-common-knife4j  文档模块
    </description>

    <dependencies>

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

        <dependency>
            <groupId>com.wx</groupId>
            <artifactId>wx-common-core</artifactId>
        </dependency>
    </dependencies>


</project>
  1. 添加 knife4j pom
  2. 添加配置类和配置属性类
import com.wx.wxcommoncore.support.WxConstant;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;

@Getter
@Setter
//@ConfigurationProperties(prefix = "wx.knife4j")
@ConfigurationProperties(prefix = WxConstant.PROPWETIES_PREFIX + WxConstant.DOT + WxKnife4jProperties.PREFIX)
public class WxKnife4jProperties {

    protected static final String PREFIX = "knife4j";

    private String title;
    private String description;
    private String name;
    private String url;
    private String email;
    private String version;

    public ApiInfo getApiInfo(){
        return new ApiInfoBuilder()
                .title(title)
                .description(description)
                .contact(new Contact(name,url,email))
                .version(version).build();
    }

}
import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * @author gh,建议使用 swagger2
 */
@EnableSwagger2
@EnableKnife4j
public class Knife4jConfig {

    @Bean
    public WxKnife4jProperties wxKnife4jProperties(){
        return new WxKnife4jProperties();
    }

    @Autowired
    private WxKnife4jProperties wxKnife4jProperties;

    @Bean
    public Docket createRestApi(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(wxKnife4jProperties.getApiInfo())
                .select()
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any()).build();
    }

}
  1. 在 META-INF 添加spring配置

spring.factories

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  com.wx.wxcommonknife4j.config.Knife4jConfig

spring-configuration-metadata.json

{
  "hints": [],
  "groups": [
    {
      "sourceType": "com.wx.wxcommonknife4j.config.WxKnife4jProperties",
      "name": "wx.knife4j",
      "type": "com.wx.wxcommonknife4j.config.WxKnife4jProperties"
    }
  ],
  "properties": [
    {
      "sourceType": "com.wx.wxcommonknife4j.config.WxKnife4jProperties",
      "name": "wx.knife4j.title",
      "description": "文档标题",
      "type": "java.lang.String"
    },
    {
      "sourceType": "com.wx.wxcommonknife4j.config.WxKnife4jProperties",
      "name": "wx.knife4j.description",
      "description": "文档描述",
      "type": "java.lang.String"
    },
    {
      "sourceType": "com.wx.wxcommonknife4j.config.WxKnife4jProperties",
      "name": "wx.knife4j.name",
      "description": "API负责人的联系信息",
      "type": "java.lang.String"
    },
    {
      "sourceType": "com.wx.wxcommonknife4j.config.WxKnife4jProperties",
      "name": "wx.knife4j.url",
      "description": "API负责人的地址",
      "type": "java.lang.String"
    },
    {
      "sourceType": "com.wx.wxcommonknife4j.config.WxKnife4jProperties",
      "name": "wx.knife4j.email",
      "description": "API负责人的email",
      "type": "java.lang.String"
    },
    {
      "sourceType": "com.wx.wxcommonknife4j.config.WxKnife4jProperties",
      "name": "wx.knife4j.version",
      "description": "接口版本",
      "type": "java.lang.String"
    }
  ]
}
  1. 其他微服务添加 pom
<dependency>
    <groupId>com.wx</groupId>
    <artifactId>wx-common-knife4j</artifactId>
</dependency>

3.界面

请求: 网关的ip:网关的port/doc.html

swagger增强knife4j在gateway中的使用入门


springcloud 脚手架(wx-cloud)

  • spring boot 2.3.3.RELEASE
  • nacos
  • geteway
  • oauth2
  • cache(spring+caffeine)
  • mybaits

上一篇:2021-10-10


下一篇:微服务基础:SpringCloud-Gateway网关核心概念&原理