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);
}
}
posted on 2018-03-14 13:17  云野  阅读(9428)  评论(0编辑  收藏  举报