Knife4j整合Spring Cloud Gateway

转载请表明出处 https://blog.csdn.net/Amor_Leo/article/details/106470845 谢谢

Knife4j整合Spring Cloud Gateway

  • 简介
  • 源码
  • 网关Gateway
    • pom
    • 配置类
    • 注意
  • 用户(或其他)服务
    • pom
    • yml
    • 配置类
    • 配置类(需要传递token的)
  • 页面

简介

是springfox-swagger的增强UI实现,为Java开发者在使用Swagger的时候,能拥有一份简洁、强大的接口文档体验
官网

源码

☞☞☞☞☞☞☞☞☞☞源码 GitHub

网关Gateway

pom

        
            com.github.xiaoymin
            knife4j-spring-boot-starter
            2.0.3
        

配置类

@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)));
    }
}
@Component
@Primary
@AllArgsConstructor
public class SwaggerProvider implements SwaggerResourcesProvider {
     
    public static final String API_URI = "/v2/api-docs";
    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(routeDefinition -> routeDefinition.getPredicates().stream()
                        .filter(predicateDefinition -> ("Path").equalsIgnoreCase(predicateDefinition.getName()))
                        .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;
    }
}


注意

在集成Spring Cloud Gateway网关的时候,会出现没有basePath的情况(即定义的例如/user、/order等微服务的前缀),在Gateway网关需要添加一个Filter实体Bean:(Spring Boot版本超过2.0.6的可以不用加)

@Component
public class SwaggerHeaderFilter extends AbstractGatewayFilterFactory {
     
    private static final String HEADER_NAME = "X-Forwarded-Prefix";

    private static final String URI = "/v2/api-docs";

    @Override
    public GatewayFilter apply(Object config) {
     
        return (exchange, chain) -> {
     
            ServerHttpRequest request = exchange.getRequest();
            String path = request.getURI().getPath();
            if (!StringUtils.endsWithIgnoreCase(path,URI )) {
     
                return chain.filter(exchange);
            }
            String basePath = path.substring(0, path.lastIndexOf(URI));
            ServerHttpRequest newRequest = request.mutate().header(HEADER_NAME, basePath).build();
            ServerWebExchange newExchange = exchange.mutate().request(newRequest).build();
            return chain.filter(newExchange);
        };
    }
}

yml


spring:
  application:
    name: service-Gateway
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true
          lowerCaseServiceId: true
      routes:
        - id: service-user
          uri: lb://service-user
          predicates:
            - Path=/user/**
          filters:
            - SwaggerHeaderFilter
            - StripPrefix=1
        - id:  service-order
          uri: lb://service-order
          predicates:
            - Path=/order/**
          filters:
            - SwaggerHeaderFilter  #指定filter
            - StripPrefix=1

用户(或其他)服务

pom

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

yml

swagger:
  enabled: true
  title: 用户服务
  base-package: com.scaffolding.sophia.admin.biz
  version: V2.0
  description: 用户服务
  license: Apache License, Version 2.0
  license-url: https://www.apache.org/licenses/LICENSE-2.0.html
  terms-of-service-url: http://localhost:8002/doc.html
  contact: [email protected]
  authorization: #有auth2 并使用以前的swagger-ui
    key-name: Authorization

配置类


@Configuration
@EnableSwagger2
@Import(BeanValidatorPluginsConfiguration.class)
@EnableKnife4j
@ConfigurationProperties(prefix="swagger")
@Getter
@Setter
public class Swagger2Config {
     

    private String title;

    private String contact;

    private String version;

    private String license;

    private String licenseUrl;

    private String termsOfServiceUrl;

    private String description;

    private String basePackage;

    /**
     * 创建RestApi 并包扫描controller
     * @return
     */
    @Bean
    public Docket createRestApi() {
     
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                //分组名称
                // .groupName("2.X版本")
                .select()
                // // 对所有api进行监控
                // .apis(RequestHandlerSelectors.any())
                .apis(RequestHandlerSelectors.basePackage(basePackage))
                //不显示错误的接口地址
                .paths(PathSelectors.any())
                //错误路径不监控
                .paths(Predicates.not(PathSelectors.regex("/error.*")))
                .build();
    }

    /**
     * 创建Swagger页面 信息
     * @return
     */
    private ApiInfo apiInfo() {
     
        return new ApiInfoBuilder().
                title(title).
                contact(contact).
                version(version).
                license(license).
                licenseUrl(licenseUrl).
                termsOfServiceUrl(termsOfServiceUrl).
                description(description)
                .build();
    }
}

配置类(需要传递token的)

@Configuration
@EnableSwagger2
@Import(BeanValidatorPluginsConfiguration.class)
@EnableKnife4j
@ConfigurationProperties(prefix="swagger")
@Getter
@Setter
public class Swagger2Config {
     

    private String title;

    private String contact;

    private String version;

    private String license;

    private String licenseUrl;

    private String termsOfServiceUrl;

    private String description;

    private String basePackage;

    /**
     * 创建RestApi 并包扫描controller
     * @return
     */
    @Bean
    public Docket createRestApi() {
     
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                //分组名称
                // .groupName("2.X版本")
                .select()
                // // 对所有api进行监控
                // .apis(RequestHandlerSelectors.any())
                .apis(RequestHandlerSelectors.basePackage(basePackage))
                //不显示错误的接口地址
                .paths(PathSelectors.any())
                //错误路径不监控
                .paths(Predicates.not(PathSelectors.regex("/error.*")))
                .build()
                .securityContexts(Lists.newArrayList(securityContext())).securitySchemes(Lists.<SecurityScheme>newArrayList(apiKey()));

    }

    /**
     * 创建Swagger页面 信息
     * @return
     */
    private ApiInfo apiInfo() {
     
        return new ApiInfoBuilder().
                title(title).
                contact(contact).
                version(version).
                license(license).
                licenseUrl(licenseUrl).
                termsOfServiceUrl(termsOfServiceUrl).
                description(description)
                .build();
    }

    private SecurityContext securityContext() {
     
        return SecurityContext.builder()
                .securityReferences(defaultAuth())
                .forPaths(PathSelectors.regex("/.*"))
                .build();
    }


    private ApiKey apiKey() {
     
        return new ApiKey("BearerToken", "Authorization", "header");
    }

    List<SecurityReference> defaultAuth() {
     
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        return Lists.newArrayList(new SecurityReference("BearerToken", authorizationScopes));
    }
}

页面

访问: http://ip:port/doc.html
Knife4j整合Spring Cloud Gateway_第1张图片
Knife4j整合Spring Cloud Gateway_第2张图片

你可能感兴趣的:(微服务,gateway,knife4j,java)