swagger在微服務中集成統一api入口


如果你的系統也是用zuul作為分布式系統的網關,同時使用swagger生成文檔,想把整個系統的文檔整合在同一個頁面上

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
@EnableSwagger2
public 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);
}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM