单体、zuul、gateway集成swagger(亲测)

分三块介绍:
一、单体应用集成swagger
二、zuul网关集成swagger
三、gateway网关集成swagger集成spring security oauth2

标题单体应用集成swagger

一、pom添加坐标

<dependency>
    <groupId>com.spring4all</groupId>
    <artifactId>swagger-spring-boot-starter</artifactId>
    <version>1.9.1.RELEASE</version>
</dependency>

二、启动类加开启注解

@EnableSwagger2Doc

三、配置文件添加配置

server:
  port: 9001
swagger:
  base-package: com.funtl.myshop.plus.business
  title: SpringCloud2.x构建XXXX项目-会员服务接口
  description: 该项目。。。。。。。
  version: 1.1
  terms-of-service-url: www.baidu.com
  contact:
    name: 作者名字
    email: [email protected]
  enabled: true
  authorization:
    key-name: Authorization

四、访问链接

localhost:9001/swagger-ui.html

zuul网关集成swagger

在单体应用集成的基础上,配置zuul网关集成swagger。

一、在网关pom添加坐标

<dependency>
    <groupId>com.spring4all</groupId>
    <artifactId>swagger-spring-boot-starter</artifactId>
    <version>1.9.1.RELEASE</version>
</dependency>

二、在网关启动类加开启注解

@EnableSwagger2Doc

三、在网关配置文件中配置路由

##服务启动端口号
server:
  port: 8080
## 配置网关反向代理    
zuul:
  routes:
    api-a:
     ### 以 /api-weixin/访问转发到会员服务
      path: /api-weixin/**
      serviceId: app-mayikt-weixin
    api-b:
        ### 以 /api-member/访问转发到订单服务
      path: /api-member/**
      serviceId: app-mayikt-member

四、在启动类上添加配置

 // 添加文档来源
	@Component
	@Primary
	class DocumentationConfig implements SwaggerResourcesProvider {
		@Override
		public List<SwaggerResource> get() {
			List resources = new ArrayList<>();
			// app-itmayiedu-order
			// 网关使用服务别名获取远程服务的SwaggerApi
			resources.add(swaggerResource("app-mayikt-member", "/app-mayikt-member/v2/api-docs", "2.0"));
			resources.add(swaggerResource("app-mayikt-weixin", "/app-mayikt-weixin/v2/api-docs", "2.0"));
			return resources;
		}

		private SwaggerResource swaggerResource(String name, String location, String version) {
			SwaggerResource swaggerResource = new SwaggerResource();
			swaggerResource.setName(name);
			swaggerResource.setLocation(location);
			swaggerResource.setSwaggerVersion(version);
			return swaggerResource;
		}

	}

五、访问链接

localhost:8080/swagger-ui.html

gateway网关集成swagger集成spring security oauth2

在单体应用集成的基础上,配置zuul网关集成swagger。
一、在网关pom添加坐标

<dependency>
    <groupId>com.spring4all</groupId>
    <artifactId>swagger-spring-boot-starter</artifactId>
    <version>1.9.1.RELEASE</version>
</dependency>

二、在网关启动类加开启注解

@EnableSwagger2Doc

三、在网关配置文件中配置路由

spring:
    # 路由网关配置
    gateway:
      # 设置与服务注册发现组件结合,这样可以采用服务名的路由策略
      discovery:
        locator:
          enabled: true
      # 配置路由规则
      routes:
        # 采用自定义路由 ID(有固定用法,不同的 id 有不同的功能,详见:https://cloud.spring.io/spring-cloud-gateway/2.0.x/single/spring-cloud-gateway.html#gateway-route-filters)
        - id: BUSINESS-OAUTH2
          # 采用 LoadBalanceClient 方式请求,以 lb:// 开头,后面的是注册在 Nacos 上的服务名
          uri: lb://business-oauth2
          # Predicate 翻译过来是“谓词”的意思,必须,主要作用是匹配用户的请求,有很多种用法
          predicates:
            # 路径匹配,以 api 开头,直接配置是不生效的,看 filters 配置
            - Path=/api-user/**
          filters:
            # 前缀过滤,默认配置下,我们的请求路径是 http://localhost:8888/business-oauth2/** 这时会路由到指定的服务
            # 此处配置去掉 1 个路径前缀,再配置上面的 Path=/api/**,就能按照 http://localhost:8888/api/** 的方式访问了
            - StripPrefix=1
        - id: BUSINESS-PROFILE
          uri: lb://business-profile
          predicates:
            - Path=/api-profile/**
          filters:
            - StripPrefix=1
        - id: CLOUD-UPLOAD
          uri: lb://cloud-upload
          predicates:
            - Path=/api-upload/**
          filters:
            - StripPrefix=1

server:
  port: 8888

# 配置日志级别,方别调试
logging:
  level:
    org.springframework.cloud.gateway: debug

四、添加3个配置类

package com.funtl.myshop.plus.gateway.config;

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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
import springfox.documentation.swagger.web.SecurityConfiguration;
import springfox.documentation.swagger.web.SecurityConfigurationBuilder;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;
import springfox.documentation.swagger.web.UiConfiguration;
import springfox.documentation.swagger.web.UiConfigurationBuilder;

import java.util.Optional;

/**
 * @Description:
 * @Author: ckk
 * @CreateDate: 2020/1/29 22:13
 */
@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)));
    }
}
package com.funtl.myshop.plus.gateway.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.GatewayFilterFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

/**
 * @Description:
 * @Author: ckk
 * @CreateDate: 2020/1/29 22:03
 */
@Component
@Slf4j
public class SwaggerHeaderFilter implements GatewayFilterFactory {
    private static final String HEADER_NAME = "X-Forwarded-Prefix";

    @Override
    public GatewayFilter apply(Object config) {
        return (exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest();
            String path = request.getURI().getPath();

            if (!StringUtils.endsWithIgnoreCase(path, SwaggerProvider.API_URI)) {
                return chain.filter(exchange);
            }

            String basePath = path.substring(0, path.lastIndexOf(SwaggerProvider.API_URI));
            log.info("SwaggerHeaderFilter X-Forwarded-Prefix :{}",basePath);
            ServerHttpRequest newRequest = request.mutate().header(HEADER_NAME, basePath).build();
            ServerWebExchange newExchange = exchange.mutate().request(newRequest).build();
            return chain.filter(newExchange);
        };
    }
}
package com.funtl.myshop.plus.gateway.config;

import lombok.AllArgsConstructor;
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;

/**
 * @Description:
 * @Author: ckk
 * @CreateDate: 2020/1/29 22:01
 */
@Component
@Primary
@AllArgsConstructor
public class SwaggerProvider implements SwaggerResourcesProvider {

    public static final String API_URI = "/v2/api-docs";
    public static final String PATH = "Path";
    private final RouteLocator routeLocator;
    private final 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;
    }
}

五、资源服务器配置放行路径

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring()
            .antMatchers("/user/login",//登录接口放行
                    "/v2/api-docs",
                    "/configuration/ui",
                    "/configuration/security",
                    "/swagger-ui.html",
                    "/webjars/**",
                    "/swagger-resources/configuration/ui", // 用来获取支持的动作
                    "/swagger-resources", // 用来获取api-docs的URI
                    "/swagger-resources/configuration/security", // 安全选项
                    "/swagger-resources/**");
}

@Override
public void configure(HttpSecurity http) throws Exception {
    http
            .exceptionHandling()
            .and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and().authorizeRequests().antMatchers(
                    "/v2/api-docs",
                    "/configuration/ui",
                    "/configuration/security",
                    "/swagger-ui.html",
                    "/webjars/**",
                    "/swagger-resources/configuration/ui", // 用来获取支持的动作
                    "/swagger-resources", // 用来获取api-docs的URI
                    "/swagger-resources/configuration/security", // 安全选项
                    "/swagger-resources/**").permitAll().anyRequest().authenticated()
            /*.and()
            .authorizeRequests()
            .antMatchers("/profile/**").hasAuthority("USER")*/;
}

六、访问链接

localhost:8888/swagger-ui.html

你可能感兴趣的:(原创)