|
| 1 | +package com.github.cadecode.uniboot.gateway.config; |
| 2 | + |
| 3 | +import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j; |
| 4 | +import lombok.RequiredArgsConstructor; |
| 5 | +import org.springframework.cloud.gateway.config.GatewayProperties; |
| 6 | +import org.springframework.cloud.gateway.route.RouteLocator; |
| 7 | +import org.springframework.cloud.gateway.support.NameUtils; |
| 8 | +import org.springframework.context.annotation.Bean; |
| 9 | +import org.springframework.context.annotation.Configuration; |
| 10 | +import org.springframework.context.annotation.Primary; |
| 11 | +import springfox.documentation.swagger.web.SwaggerResource; |
| 12 | +import springfox.documentation.swagger.web.SwaggerResourcesProvider; |
| 13 | + |
| 14 | +import java.util.HashSet; |
| 15 | +import java.util.List; |
| 16 | +import java.util.Map; |
| 17 | +import java.util.Set; |
| 18 | +import java.util.stream.Collectors; |
| 19 | + |
| 20 | +/** |
| 21 | + * Gateway swagger 聚合配置 |
| 22 | + * |
| 23 | + * @author Cade Li |
| 24 | + * @since 2023/7/29 |
| 25 | + */ |
| 26 | +@RequiredArgsConstructor |
| 27 | +@EnableKnife4j |
| 28 | +@Configuration |
| 29 | +public class GatewaySwaggerConfig { |
| 30 | + |
| 31 | + /** |
| 32 | + * 网关路由 |
| 33 | + */ |
| 34 | + private final RouteLocator routeLocator; |
| 35 | + |
| 36 | + private final GatewayProperties gatewayProperties; |
| 37 | + |
| 38 | + @Primary |
| 39 | + @Bean |
| 40 | + public SwaggerResourcesProvider resourcesProvider() { |
| 41 | + return new SwaggerResourcesProvider() { |
| 42 | + /** |
| 43 | + * 聚合服务接口 |
| 44 | + */ |
| 45 | + @Override |
| 46 | + public List<SwaggerResource> get() { |
| 47 | + Set<String> routeSet = new HashSet<>(); |
| 48 | + // 获取网关中配置的 route |
| 49 | + routeLocator.getRoutes().subscribe(o -> routeSet.add(o.getId())); |
| 50 | + return gatewayProperties.getRoutes().stream() |
| 51 | + .filter(o -> routeSet.contains(o.getId())) |
| 52 | + .flatMap(o -> o.getPredicates().stream() |
| 53 | + .filter(p -> "Path".equalsIgnoreCase(p.getName())) |
| 54 | + .map(p -> geneSwaggerResource(o.getId(), p.getArgs())) |
| 55 | + .collect(Collectors.toList()) |
| 56 | + .stream()) |
| 57 | + .collect(Collectors.toList()); |
| 58 | + } |
| 59 | + |
| 60 | + }; |
| 61 | + } |
| 62 | + |
| 63 | + private SwaggerResource geneSwaggerResource(String name, Map<String, String> args) { |
| 64 | + // 获取 swagger2 location |
| 65 | + String location = args.get(NameUtils.GENERATED_NAME_PREFIX + "0").replace("/**", "/v2/api-docs"); |
| 66 | + SwaggerResource swaggerResource = new SwaggerResource(); |
| 67 | + swaggerResource.setName(name); |
| 68 | + swaggerResource.setLocation(location); |
| 69 | + swaggerResource.setSwaggerVersion("2.0"); |
| 70 | + return swaggerResource; |
| 71 | + } |
| 72 | +} |
0 commit comments