要在Spring Cloud Gateway中整合Knife4j(Swagger的增强工具),实现网关聚合接口文档,你可以按照以下步骤操作:
- 添加依赖:在
pom.xml
文件中添加Knife4j和Swagger的依赖:
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>3.0.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
- 配置Swagger:创建一个Swagger配置类,配置Swagger的基本信息和扫描的包路径:
@Configuration
@EnableSwagger2WebFlux
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("My API")
.description("API Documentation")
.version("1.0")
.build();
}
}
- 配置Knife4j:创建一个Knife4j配置类,配置Knife4j的基本信息和扫描的包路径:
@Configuration
public class Knife4jConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.controller"))
.paths(PathSelectors.any())
.build()
.securityContexts(Collections.singletonList(securityContext()))
.securitySchemes(Collections.singletonList(apiKey()));
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("My API")
.description("API Documentation")
.version("1.0")
.build();
}
private ApiKey apiKey() {
return new ApiKey("token", "token", "header");
}
private SecurityContext securityContext() {
return SecurityContext.builder()
.securityReferences(defaultAuth())
.forPaths(PathSelectors.regex("^(?!auth).*$"))
.build();
}
private List<SecurityReference> defaultAuth() {
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
return Collections.singletonList(new SecurityReference("token", authorizationScopes));
}
}
- 配置Gateway:在Gateway的配置文件(如
application.yml
)中添加Knife4j的相关配置:
spring:
cloud:
gateway:
routes:
- id: swagger-route
uri: lb://swagger-ui
predicates:
- Path=/swagger-ui/**
filters:
- StripPrefix=2
这样配置后,访问http://localhost:8080/swagger-ui/index.html
即可查看整合了Knife4j的网关聚合接口文档。