微服务使用Gateway网关整合Swagger2文档

微服务使用Gateway网关整合Swagger2文档

完整项目地址

1.初始化项目

开发工具:IDEA

环境:SpringBoot 2.3.0 JDK1.8+

springcloud 父工程
----common 公共依赖模块
----gateway 网关
----demo1 微服务1
----demo1 微服务2

2.maven依赖

1.公共模块引入依赖

<dependency>
    <groupId>io.springfoxgroupId>
    <artifactId>springfox-swagger2artifactId>
    <version>2.9.2version>
dependency>
<dependency>
    <groupId>io.springfoxgroupId>
    <artifactId>springfox-swagger-uiartifactId>
    <version>2.9.2version>
dependency>

2. 其他模块引入公共模块


<dependency>
    <groupId>com.mwgroupId>
    <artifactId>commonartifactId>
    <version>1.0-SNAPSHOTversion>
dependency>

3.微服务模块配置文件

demo1与demo2配置相似 application.properties

spring.application.name=demo1

server.port=8080

server.servlet.context-path=/demo1

gateway application.properties


# 应用服务名
spring.application.name=gateway
# 应用服务 WEB 访问端口
server.port=88

gateway application.yml


spring:
  cloud:
    gateway:
      discovery:
        locator:
          enabled: false #这里演示不用注册中心,否则设置为true 开启从注册中心动态创建路由的功能,利用微服务名进行路由
      routes:
        - id: demo1 #demo1   #路由的ID,没有固定规则但要求唯一,建议配合服务名
          uri: http://localhost:8080          #匹配后提供服务的路由地址
#          uri: lb://demo1 #匹配后提供服务的路由地址
          predicates:
            - Path=/demo1/**         # 断言,路径相匹配的进行路由
        - id: demo2 #demo2    #路由的ID,没有固定规则但要求唯一,建议配合服务名
          uri: http://localhost:8081         #匹配后提供服务的路由地址
#          uri: lb://demo2 #匹配后提供服务的路由地址
          predicates:
            - Path=/demo2/**         # 断言,路径相匹配的进行路由

4.编码

demo1、demo2 添加SwaggerConfig

@EnableSwagger2
@Configuration
public class SwaggerConfig {
     

    private boolean swagger_is_enable = true;

    @Bean
    public Docket buildDocket() {
     
        return new Docket(DocumentationType.SWAGGER_2)
                .enable(swagger_is_enable)
                .apiInfo(buildApiInf())
                .select()
                // swagger 扫描 controller 包路径
                .apis(RequestHandlerSelectors.basePackage("com.mw.demo.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo buildApiInf() {
     
        return new ApiInfoBuilder()
                .title("Demo1整合swagger")
                .version("1.0")
                .build();
    }


}

gateway添加SwaggerConfig

@Configuration
@Primary
public class SwaggerConfig implements SwaggerResourcesProvider {
     
    public static final String API_URI = "/v2/api-docs";
    private final RouteLocator routeLocator;
    private final GatewayProperties gatewayProperties;

    public SwaggerConfig(RouteLocator routeLocator, GatewayProperties gatewayProperties) {
     
        this.routeLocator = routeLocator;
        this.gatewayProperties = gatewayProperties;
    }


    @Override
    public List<SwaggerResource> get() {
     
        List<SwaggerResource> resources = new ArrayList<>();
        List<String> routes = new ArrayList<>();
        //取出gateway的route
        routeLocator.getRoutes().subscribe(route -> routes.add(route.getId()));
        //结合配置的route-路径(Path),和route过滤,只获取有效的route节点
        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;
    }

}

gateway添加SwaggerController

@RestController
public class SwaggerController {
     

    @Autowired(required = false)
    private SecurityConfiguration securityConfiguration;

    @Autowired(required = false)
    private UiConfiguration uiConfiguration;

    @Autowired
    private SwaggerConfig swaggerResources;

    @Autowired
    public SwaggerController(SwaggerConfig swaggerResources) {
     
        this.swaggerResources = swaggerResources;
    }


    @GetMapping("/swagger-resources/configuration/security")
    public Mono<ResponseEntity<SecurityConfiguration>> securityConfiguration() {
     
        return Mono.just(new ResponseEntity<>(
                Optional.ofNullable(securityConfiguration).orElse(SecurityConfigurationBuilder.builder().build()), HttpStatus.OK));
    }

    @GetMapping("/swagger-resources/configuration/ui")
    public Mono<ResponseEntity<UiConfiguration>> uiConfiguration() {
     
        return Mono.just(new ResponseEntity<>(
                Optional.ofNullable(uiConfiguration).orElse(UiConfigurationBuilder.builder().build()), HttpStatus.OK));
    }

    @GetMapping("/swagger-resources")
    public Mono<ResponseEntity> swaggerResources() {
     
        return Mono.just((new ResponseEntity<>(swaggerResources.get(), HttpStatus.OK)));
    }

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

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


}

你可能感兴趣的:(SpringBoot学习,java)