SpringCloudGateway整合swagger3文档
Spring Cloud Gateway 整合 Swagger 3 文档需要通过自定义过滤器来转发 Swagger 的 API 文档。以下是一个简单的示例:
- 添加依赖(确保你已经添加了Spring Cloud Gateway和Spring Boot的相关依赖):
<!-- Swagger 3 依赖 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
- 配置 Swagger:
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
}
- 自定义过滤器转发 Swagger 文档:
@Component
public class SwaggerHeaderFilter extends AbstractGatewayFilterFactory {
@Override
public GatewayFilter apply(Object config) {
return (exchange, chain) -> {
ServerHttpRequest request = exchange.getRequest();
String path = request.getURI().getPath();
// 仅转发 Swagger 的 API 文档请求
if (path.startsWith("/swagger") || path.startsWith("/v3/api-docs")) {
ServerHttpRequest newRequest = request.mutate()
.header(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*")
.build();
return chain.filter(exchange.mutate().request(newRequest).build());
}
return chain.filter(exchange);
};
}
}
- 在
application.yml
或application.properties
中配置 SwaggerHeaderFilter:
spring:
cloud:
gateway:
routes:
- id: swagger_route
uri: http://your-backend-service
predicates:
- Path=/your-backend-service/**
filters:
- SwaggerHeaderFilter
确保替换 your-backend-service
为你的后端服务的实际路径。
这样配置后,当你访问 http://your-gateway-service/swagger-ui.html
或 http://your-gateway-service/v3/api-docs
时,Gateway 会转发请求到后端服务,并返回 Swagger 文档。
评论已关闭