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);
}
}

转载于:https://www.cnblogs.com/renzl/p/8566977.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值