1. 介绍
在微服务架构中,通常会有多个子服务提供不同的功能,并通过网关进行统一的访问。而使用Swagger来生成和查看接口文档可以极大地提高开发效率和团队协作。本文将介绍如何使用SpringCloud Gateway和knife4j插件来实现通过网关统一查看所有子服务的Swagger接口文档。
2. 环境准备
在开始前,需要确保以下环境已经搭建好:
- JDK 8+
- Maven
- SpringBoot 2.x
- SpringCloud Greenwich.RELEASE
3. 添加依赖
首先,在主网关项目的pom.xml
中添加如下依赖:
<dependency>
<groupId>com.spring4all</groupId>
<artifactId>swagger-spring-boot-starter</artifactId>
<version>1.9.0.RELEASE</version>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>2.0.6</version>
</dependency>
4. 配置Swagger和knife4j
在主网关项目的配置文件(application.yml
或application.properties
)中,添加如下配置:
spring:
profiles:
active: dev # 指定当前环境,如dev、test、prod等
cloud:
gateway:
routes:
- id: swagger_route
uri: lb://swagger-services # 子服务的注册名
predicates:
- Path=/swagger/**
filters:
- StripPrefix=1
添加Swagger和knife4j的配置类,创建一个SwaggerConfig
类:
@Configuration
@EnableSwagger2WebMvc
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("API文档")
.description("SpringCloud Gateway统一聚合Swagger接口文档")
.version("1.0")
.build();
}
}
5. 启动项目
启动主网关项目后,访问如下地址可以查看网关的Swagger接口文档:
http://localhost:端口/swagger-ui.html
其中端口
为主网关项目的端口号。
6. 聚合子服务接口文档
为了能够通过主网关统一查看所有子服务的接口文档,我们需要在子服务中添加Swagger和knife4j的依赖,并配置Swagger。
在每个子服务的pom.xml
中添加如下依赖:
<dependency>
<groupId>com.spring4all</groupId>
<artifactId>swagger-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
</dependency>
创建一个SwaggerConfig
类,配置Swagger:
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.controller")) // 子服务的Controller包路径
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("API文档")
.description("子服务接口文档")
.version("1.0")
.build();
}
}
7. 查看接口文档
启动各个子服务后,访问主网关的Swagger接口文档地址:
http://localhost:主网关端口/swagger-ui.html
在网关的Swagger界面中,可以看到左侧的服务列表中已经聚合了所有子服务的接口文档。点击对应的服务名称,即可查看该服务的接口文档详情。
8. 结束语
通过使用SpringCloud Gateway和knife4j,我们可以实现通过网关统一查看所有子服务的Swagger接口文档。这样可以方便地查看和测试各个服务的接口,提高开发效率和团队协作能力。欢迎大家使用和探索更多的微服务架构相关技术。
希望本文对大家有所帮助,如有任何问题或建议,欢迎留言讨论。谢谢阅读!
本文来自极简博客,作者:晨曦吻,转载请注明原文链接:SpringCloud Gateway网关统一聚合Swagger接口文档(knife4j)