swagger在微服务中集成统一api入口

若是你的系统也是用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);    }}
相关文章
相关标签/搜索