springgateway集成knife4j

微服务应用(除了网关):

pom文件


        <dependency>
            <groupId>com.github.xiaoymingroupId>
            <artifactId>knife4j-spring-boot-autoconfigureartifactId>
        dependency>






bootstrap.yml

# Tomcat
server:
  port: 9208

# Spring
spring:
  application:
    # 应用名称
    name: forum-file
  profiles:
    # 环境配置
    active: dev
  cloud:
    nacos:
      discovery:
        # 服务注册地址
        server-addr: 127.0.0.0:8858
      config:
        # 配置中心地址
        server-addr: 127.0.0.0:8858
        # 配置文件格式
        file-extension: yml
        namespace: 433ed0c8-55ff-4e84-8bbc-704cfaf21bbd
        # 共享配置
        shared-configs:
          - application-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension}

配置文件

package com.linmain.swagger.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;

/**
 * @Author linzhuoqi
 * @Date 2022/5/15
 * @Eamil [email protected]
 * @Version
 * @Description   Swagger2配置信息
 */
@Configuration
@EnableSwagger2WebMvc
@Import(BeanValidatorPluginsConfiguration.class)
public class Swagger2Config {


    @Value("${spring.application.name}")
    private String serviceName;

    @Bean
    public Docket webApiConfig(){

        return new Docket(DocumentationType.SWAGGER_2)
                .groupName(serviceName)
                .apiInfo(webApiInfo())
                .select()
                //PathSelectors.any()任何请求都扫描
                .paths(PathSelectors.any())
                .build();

    }

    private ApiInfo webApiInfo(){

        return new ApiInfoBuilder()
                .title(serviceName)
                .description("接口文档")
                .version("1.0")
                .contact(new Contact("LinMain", "http://baidu.com", "[email protected]"))
                .build();
    }

}

网关:

pom文件


                <dependency>
                    <groupId>com.github.xiaoymingroupId>
                    <artifactId>knife4j-spring-uiartifactId>
                dependency>


                <dependency>
                    <groupId>com.github.xiaoymingroupId>
                    <artifactId>knife4j-spring-boot-autoconfigureartifactId>
                dependency>

java文件

package com.linmain.gateway.utils;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.route.RouteLocator;
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;
import java.util.Set;
import java.util.TreeSet;

/**
 * @Author linzhuoqi
 * @Date 2023/2/8
 * @Eamil [email protected]
 * @Version
 * @Description  通过网关的路由获取所有的swagger资源
 */
@Component
@RequiredArgsConstructor
@Primary
@Slf4j
public class MySwaggerResourceProvider implements SwaggerResourcesProvider {

    /**
     * swagger2默认的url后缀
     */
    private static final String SWAGGER2_URL = "/v2/api-docs";

    /**
     * 路由定位器
     */
    private final RouteLocator routeLocator;

    /**
     * 网关应用名称
     */
    @Value("${spring.application.name}")
    private String gatewayName;

    /**
     * 获取 Swagger 资源
     */
    @Override
    public List<SwaggerResource> get() {
        List<SwaggerResource> resources = new ArrayList<>();

        //可能重复,使用这个防止重复
        Set<String> routeHosts = new TreeSet<>();
        // 1. 获取路由Uri 中的Host=> 服务注册则为服务名=》app-service001
        routeLocator.getRoutes()
                //得到不为空的
                .filter(route -> route.getUri().getHost() != null)
                //得到不是网关的
                .filter(route -> !gatewayName.equals(route.getUri().getHost()))
                //添加到routeHosts
                .subscribe(route -> routeHosts.add(route.getUri().getHost()));
        // 2. 创建自定义资源
        for (String routeHost : routeHosts) {

            log.info("===========输出路由地址"+routeHost+"==============");

            // 后台访问添加服务名前缀
            String serviceUrl = "/" + routeHost + SWAGGER2_URL+"?group="+routeHost;
            // 创建Swagger 资源
            SwaggerResource swaggerResource = new SwaggerResource();
            swaggerResource.setUrl(serviceUrl); // 设置访问地址
            swaggerResource.setName(routeHost); // 设置名称
            swaggerResource.setSwaggerVersion("2.0.0");
            resources.add(swaggerResource);
        }
        return resources;
    }
}
package com.linmain.gateway.controller;

import com.linmain.gateway.utils.MySwaggerResourceProvider;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.swagger.web.SwaggerResource;

import java.util.List;

/**
 * @Author linzhuoqi
 * @Date 2023/2/8
 * @Eamil [email protected]
 * @Version
 * @Description  覆盖重写原本的地址(swagger)
 */
@RestController
@RequestMapping("/swagger-resources")
@RequiredArgsConstructor
public class SwaggerResourceController {


    private final MySwaggerResourceProvider swaggerResourceProvider;

    @RequestMapping
    public ResponseEntity<List<SwaggerResource>> swaggerResources() {
        return new ResponseEntity<>(swaggerResourceProvider.get(), HttpStatus.OK);
    }
}


你可能感兴趣的:(java,spring,spring,boot)