记得我的mall-swarm微服务项目中,没有做API文档聚合,访问每个服务的API文档都需要访问单独的swagger-ui.html页面,既然我们使用了微服务,就应该有统一的API文档入口,最近发现knife4j有这方面的支持,本文将详细介绍其实现,希望对大家有所帮助!
前置知识
我们将采用Nacos作为注册中心,Gateway作为网关,使用knife4j来生成API文档
应用架构
我们理想的解决方案应该是这样的,网关作为API文档的统一入口,网关聚合所有微服务的文档,通过在网关进行切换来实现对其他服务API文档的访问。
相关服务划分:
- micro-knife4j-gateway:网关服务,作为微服务API文档的访问入口,聚合所有API文档,需要引入文档前端UI包;
- micro-knife4j-user:用户服务,普通API服务,不需要引入文档前端UI包;
- micro-knife4j-order:订单服务,普通API服务,不需要引入文档前端UI包。
具体实现
下面详细介绍下Spring Cloud Gateway + knife4j 聚合API文档的具体实现,依次搭建用户服务、订单服务和网关服务。
micro-knife4j-user
我们首先来搭建用户服务,一个普通的API服务,很简单,仅需三步即可集成knife4j。
- 在pom.xml中添加相关依赖,一个SpringBoot的web功能依赖,knife4j的微服务依赖(不包含API文档的前端UI包);
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-micro-spring-boot-starter</artifactId>
</dependency>
</dependencies>
- 在application.yml这添加相关配置,配置一下Nacos注册中心即可;
server:
port: 9501
spring:
profiles:
active: dev
application:
name: micro-knife4j-user
cloud:
nacos:
discovery:
server-addr: localhost:8848
management:
endpoints:
web:
exposure:
include: "*"
- 添加Swagger相关配置,非常常规的配置,添加@EnableKnife4j注解开启knife4j的增强功能。
/**
* Swagger API相关配置
*/
@Configuration
@EnableSwagger2
@EnableKnife4j
public class Swagger2Config {
@Bean
public Docket createRestApi(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.macro.cloud.controller"