|
@@ -0,0 +1,52 @@
|
|
1
|
+package com.community.huiju.swagger;
|
|
2
|
+
|
|
3
|
+import org.springframework.cloud.gateway.config.GatewayProperties;
|
|
4
|
+import org.springframework.cloud.gateway.route.RouteLocator;
|
|
5
|
+import org.springframework.cloud.gateway.support.NameUtils;
|
|
6
|
+import org.springframework.context.annotation.Primary;
|
|
7
|
+import org.springframework.stereotype.Component;
|
|
8
|
+import springfox.documentation.swagger.web.SwaggerResource;
|
|
9
|
+import springfox.documentation.swagger.web.SwaggerResourcesProvider;
|
|
10
|
+
|
|
11
|
+import java.util.ArrayList;
|
|
12
|
+import java.util.List;
|
|
13
|
+
|
|
14
|
+/**
|
|
15
|
+ * @Primary 注解的实例优先于其他实例被注入
|
|
16
|
+ */
|
|
17
|
+@Component
|
|
18
|
+@Primary
|
|
19
|
+public class GatewaySwaggerProvider implements SwaggerResourcesProvider {
|
|
20
|
+ public static final String API_URI = "/v2/api-docs";
|
|
21
|
+ private final RouteLocator routeLocator;
|
|
22
|
+ private final GatewayProperties gatewayProperties;
|
|
23
|
+
|
|
24
|
+ public GatewaySwaggerProvider(RouteLocator routeLocator, GatewayProperties gatewayProperties) {
|
|
25
|
+ this.routeLocator = routeLocator;
|
|
26
|
+ this.gatewayProperties = gatewayProperties;
|
|
27
|
+ }
|
|
28
|
+
|
|
29
|
+ @Override
|
|
30
|
+ public List<SwaggerResource> get() {
|
|
31
|
+ List<SwaggerResource> resources = new ArrayList<>();
|
|
32
|
+ List<String> routes = new ArrayList<>();
|
|
33
|
+ //取出Spring Cloud Gateway中的route
|
|
34
|
+ routeLocator.getRoutes().subscribe(route -> routes.add(route.getId()));
|
|
35
|
+ //结合application.yml中的路由配置,只获取有效的route节点
|
|
36
|
+ gatewayProperties.getRoutes().stream().filter(routeDefinition -> routes.contains(routeDefinition.getId()))
|
|
37
|
+ .forEach(routeDefinition -> routeDefinition.getPredicates().stream()
|
|
38
|
+ .filter(predicateDefinition -> ("Path").equalsIgnoreCase(predicateDefinition.getName()))
|
|
39
|
+ .forEach(predicateDefinition -> resources.add(swaggerResource(routeDefinition.getId(),
|
|
40
|
+ predicateDefinition.getArgs().get(NameUtils.GENERATED_NAME_PREFIX + "0")
|
|
41
|
+ .replace("/**", API_URI)))));
|
|
42
|
+ return resources;
|
|
43
|
+ }
|
|
44
|
+
|
|
45
|
+ private SwaggerResource swaggerResource(String name, String location) {
|
|
46
|
+ SwaggerResource swaggerResource = new SwaggerResource();
|
|
47
|
+ swaggerResource.setName(name);
|
|
48
|
+ swaggerResource.setLocation(location);
|
|
49
|
+ swaggerResource.setSwaggerVersion("2.0");
|
|
50
|
+ return swaggerResource;
|
|
51
|
+ }
|
|
52
|
+}
|