SpringCloud Zuul+Swagger2接口文档管理
整个微服务的系统里面,所有的接口都需要展现给前端开发人员,所以,可以在Zuul里面加上Swagger实现相应的效果,如图:
首先是项目依赖:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
Zuul-server
首先配置SwaggerConfig
SwaggerConfig
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("测试系统搭建")
.description("测试系统接口文档说明")
.termsOfServiceUrl("http://localhost:1006")
.contact(new Contact("td", "", "11111111@qq.com"))
.version("1.0")
.build();
}
@Bean
UiConfiguration uiConfig() {
return new UiConfiguration(null, "list", "alpha", "schema",
UiConfiguration.Constants.DEFAULT_SUBMIT_METHODS, false, true, 60000L);
}
}
接着是DocumentationConfig
DocumentationConfig
@Component
@Primary
public class DocumentationConfig implements SwaggerResourcesProvider
{
@Override
public List<SwaggerResource> get() {
List resources = new ArrayList<>();
resources.add(swaggerResource("认证系统", "/auth/v2/api-docs", "2.0"));
resources.add(swaggerResource("XX系统", "/base/v2/api-docs", "2.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;
}
}
其他系统配置都一样
xx-server
项目依赖跟上面都一样,其他的就是一个配置文件搞定
SwaggerConfig
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.td.XX.controller"))
.apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("XX系统api")
.description("XX系统接口文档说明")
.contact(new Contact("td", "", "111111111111@qq.com"))
.version("1.0")
.build();
}
@Bean
UiConfiguration uiConfig() {
return new UiConfiguration(null, "list", "alpha", "schema",
UiConfiguration.Constants.DEFAULT_SUBMIT_METHODS, false, true, 60000L);
}
}
最主要的就是,如果系统里面有Oauth2的SSO认证的话,一定要放开权限校验,否则就会报错:failed to load api definition.
。
好了,Zuul+swagger的基本配置就是这样了。