swagger在微服务中集成统一api入口
如果你的系统也是用zuul作为分布式系统的网关,同时使用swagger生成文档,想把整个系统的文档整合在同一个页面上pom.xml引用<dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger2</artifactId>...
·
如果你的系统也是用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<SwaggerResource> resources = new ArrayList<>(); List<Route> routes = routeLocator.getRoutes(); for (Route route:routes) { resources.add(swaggerResource(route.getId(), route.getFullPath().replace("**", "v2/api-docs"))); } return resources; } private SwaggerResource swaggerResource(String name, String location) { SwaggerResource swaggerResource = new SwaggerResource(); swaggerResource.setName(name); swaggerResource.setLocation(location); swaggerResource.setSwaggerVersion("2.0"); 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(); } }
更多推荐
已为社区贡献1条内容
所有评论(0)