Swagger2API 接口管理-Zuul整合Swagger

课题引入

随着微服务架构体系的发展和应用, 为了前后端能够更好的集成与对接,同时
为了项目的方便交付,每个项目都需要提供相应的 API 文档。
来源: PC 端、微信端、 H5 端、移动端(安卓和 IOS 端)
传统的 API 文档编写存在以下几个痛点 :
对 API 文档进行更新的时候,需要通知前端开发人员,导致文档更新交流不及时;
API 接口返回信息不明确
大公司中肯定会有专门文档服务器对接口文档进行更新。
缺乏在线接口测试,通常需要使用相应的 API 测试工具,比如 postman、 SoapUI

接口文档太多,不便于管理
为了解决传统 API 接口文档维护的问题,为了方便进行测试后台 Restful 接口并
实现动态的更新,因而引入 Swagger 接口工具。Swagger 具有以下优点1.功能丰富:支持多种注解,自动生成接口文档界面,支持在界面测试 API 接口
功能;
2.及时更新:开发过程中花一点写注释的时间,就可以及时的更新 API 文档,省
心省力;
3.整合简单:通过添加 pom 依赖和简单配置,内嵌于应用中就可同时发布 API
接口文档界面,不需要部署独立服务。

Swagger 2.0 集成配置

maven依赖信息

<!-- swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.8.0</version>
</dependency>

SwaggerConfig

@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select()
// api 扫包
.apis(RequestHandlerSelectors.basePackage("com.blackcatfish.api")).paths(PathSelectors.any()).buil
d();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder().title("资产库接口文档").description("黑鲶鱼制作")
// .contact(contact)
.version("1.0").build();
}
}

Zull 整合 Swagger 管理微服务所有 API

<!-- swagger-spring-boot  在每个服务pom文件中加入此依赖-->
<dependency>
<groupId>com.spring4all</groupId>
<artifactId>swagger-spring-boot-starter</artifactId>
<version>1.7.0.RELEASE</version>
</dependency>

application.yml 配置
Api 接口扫描范围

swagger:
base-package: com.itmayeidu.api

项目启动引入开启生成文档
@EnableSwagger2Doc


ZuulGateway 网关

@SpringBootApplication
@EnableEurekaClient
@EnableZuulProxy
@EnableSwagger2Doc
public class AppGateWay {
// @EnableZuulProxy 开启网关代理
public static void main(String[] args) {
SpringApplication.run(AppGateWay.class, args);
}
// zuul 配置能够使用 config 实现实时更新
@RefreshScope
@ConfigurationProperties("zuul")
public ZuulProperties zuulProperties() {
return new ZuulProperties();
}

 

 

@Component
@Primary
class DocumentationConfig implements SwaggerResourcesProvider {
@Override
public List<SwaggerResource> get() {
List resources = new ArrayList<>();
// app-itmayiedu-order
resources.add(swaggerResource("app-article",
"/api-article/v2/api-docs", "2.0"));
resources.add(swaggerResource("app-page",
"/api-page/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;
}
}
}

网关服务依赖

<dependency>
<groupId>com.spring4all</groupId>
<artifactId>swagger-spring-boot-starter</artifactId>
<version>1.7.0.RELEASE</version>
</dependency>

这样就可以所有的服务接口信息放到一个swagger 里面了

posted @ 2020-03-27 15:16  BlackCatFish  阅读(312)  评论(0编辑  收藏  举报