若是你的系統也是用zuul做爲分佈式系統的網關,同時使用swagger生成文檔,想把整個系統的文檔整合在同一個頁面上spring
pom.xml引用數據庫
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>
@Component
@Primary
public class GetWayResource implements SwaggerResourcesProvider {
@Autowired
private final DiscoveryClient discoveryClient;
@Autowired
private final RouteLocator routeLocator;
public GetWayResource(DiscoveryClient discoveryClient, RouteLocator routeLocator) {
this.discoveryClient = discoveryClient;
this.routeLocator = routeLocator;
}
@Override
public List<SwaggerResource> get() {
List resources = new ArrayList<>();
resources.add(swaggerResource("default", "/v2/api-docs","1.0"));
List<Route> routes= routeLocator.getRoutes();
routes.forEach(route->{
resources.add(swaggerResource(route.getId(), route.getFullPath().replace("**", "v2/api-docs"), "1.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;
}
}
經過zuul的api獲取全部的Route鏈接
若是沒有使用zuul網關的話,
List<Route> routes= routeLocator.getRoutes();
routes.forEach(route->{
resources.add(swaggerResource(route.getId(), route.getFullPath().replace("**", "v2/api-docs"), "1.0"));
});
這裏的數據來源能夠經過集中配置或者數據庫裏獲取等方式獲得每一個服務的訪問鏈接。
每一個類必需要配置上該註冊信息
@Configuration@EnableSwagger2public class Swagger2Config { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.zhongfei.springcloudeurekaserverdemo")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("中非網api文檔中心") .description("簡單優雅的restfun風格,") .version("1.0") .build(); } @Bean UiConfiguration uiConfig() { return new UiConfiguration(null, "list", "alpha", "schema", UiConfiguration.Constants.DEFAULT_SUBMIT_METHODS, false, true, 60000L); }}