SpringCloudGateway集成Swagger3

  1. 后台服务Swagger配置
package com.synda.conmmon.config;

import lombok.Data;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import springfox.documentation.builders.*;
import springfox.documentation.schema.ScalarType;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

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

/**
 * @author hzy
 * @date 2021-02-13
 */
@Component
@Data
@Configuration
@EnableSwagger2
public class SwaggerConfiguration {
    /**
     * 对c端的接口文档
     * @return 返回Docket
     */
    @Bean
    public Docket webApiDoc(){
        //enable(true) 定义是否开启swagger,false是关闭,可以通过变量去控制
        return new Docket(DocumentationType.OAS_30)
                .pathMapping("/")
                .enable(true)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.synda.seckill.user"))
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.ant("/api/**"))
                .build()
                .globalRequestParameters(requestParameters()) //设置统一请求头
                .globalResponses(HttpMethod.GET,responses()) //设置get请求响应状态码
                .globalResponses(HttpMethod.POST,responses()); //设置post请求响应状态码
    }
    /**
     * 设置文档信息
     * @return 返回ApiInfo信息
     */
    private ApiInfo apiInfo(){
        return new ApiInfoBuilder().title("Spring-cloud-alibaba学习接口文档").description("微服务接口文档").contact(new Contact("xxx","https://xdclass.net","[email protected]")).version("V1.0").build();
    }

    /**
     * 设置自定义请求头
     * @return 返回请求头对象List
     */
    private List<RequestParameter> requestParameters(){
        List<RequestParameter> parameters = new ArrayList<>();
        parameters.add(new RequestParameterBuilder().name("token").description("登录令牌").in(ParameterType.HEADER).query(q->q.model(m->m.scalarModel(ScalarType.STRING))).required(false).build());
        return parameters;
    }

    /**
     * 设置自定义返回状态码
     * @return 响应对象List
     */
    private List<Response> responses(){
        List<Response> responses = new ArrayList<>();
        responses.add(new ResponseBuilder()
        .code("4xx").description("错误返回").build());
        return responses;
    }
}

  1. 网关配置
package com.synda.seckill.gateway.config;

import org.springframework.beans.factory.annotation.Autowired;
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.HashSet;
import java.util.List;
import java.util.Set;
@Primary
@Component
public class MySwaggerResourceProvider implements SwaggerResourcesProvider {

    /**
     * swagger2默认的url后缀,此处,不管你是2还是3版本的swagger,都是v2,如果使用v3,调用接口时,服务名前缀就会丢失,别问为什么,问就是通了一个宵
     */
    private static final String SWAGGER2URL = "/v2/api-docs";

    /**
     * 网关路由
     */
    private final RouteLocator routeLocator;

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

    @Autowired
    public MySwaggerResourceProvider(RouteLocator routeLocator) {
        this.routeLocator = routeLocator;
    }

    @Override
    public List<SwaggerResource> get() {
        List<SwaggerResource> resources = new ArrayList<>();
        List<String> routeHosts = new ArrayList<>();
        // 获取所有可用的host:serviceId
        routeLocator.getRoutes().filter(route -> route.getUri().getHost() != null)
                .filter(route -> !self.equals(route.getUri().getHost()))
                .subscribe(route -> routeHosts.add(route.getUri().getHost()));

        // 记录已经添加过的server,存在同一个应用注册了多个服务在eureka上
        Set<String> dealed = new HashSet<>();
        routeHosts.forEach(instance -> {
            // 拼接url
            String url = "/" + instance + SWAGGER2URL;
            if (!dealed.contains(url)) {
                dealed.add(url);
                SwaggerResource swaggerResource = new SwaggerResource();
                swaggerResource.setUrl(url);
                swaggerResource.setName(instance);
                resources.add(swaggerResource);
            }
        });
        return resources;
    }
}

package com.synda.seckill.gateway.controller;


import com.synda.seckill.gateway.config.MySwaggerResourceProvider;
import org.springframework.beans.factory.annotation.Autowired;
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.*;

import java.util.List;

/**
 * swagger聚合接口,三个接口都是swagger-ui.html需要访问的接口
 */
@RestController
@RequestMapping("/swagger-resources")
public class SwaggerResourceController {

    private MySwaggerResourceProvider mySwaggerResourceProvider;

    @Autowired
    public SwaggerResourceController(MySwaggerResourceProvider mySwaggerResourceProvider) {
        this.mySwaggerResourceProvider = mySwaggerResourceProvider;
    }

    @RequestMapping(value = "/configuration/security")
    public ResponseEntity<SecurityConfiguration> securityConfiguration() {
        return new ResponseEntity<>(SecurityConfigurationBuilder.builder().build(), HttpStatus.OK);
    }

    @RequestMapping(value = "/configuration/ui")
    public ResponseEntity<UiConfiguration> uiConfiguration() {
        return new ResponseEntity<>(UiConfigurationBuilder.builder().build(), HttpStatus.OK);
    }

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

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