确保已经在依赖中添加了Swagger和Swagger UI的相关依赖:
compile group: 'io.springfox', name: 'springfox-swagger2', version: '2.9.2'
compile group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.9.2'
在API网关配置类中,添加Swagger资源(静态页面)的路由配置:
@Bean
public RouterFunction swaggerRouterFunction() {
return RouterFunctions.resources("/swagger/**", new ClassPathResource("META-INF/resources/"));
}
在Swagger配置类中,添加对应的注解,以开启Swagger文档的生成与展示:
@Configuration
@EnableSwagger2WebFlux
public class SwaggerConfiguration {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("API Documentation")
.description("API Documentation")
.version("1.0")
.build();
}
}
在spring-cloud-starter-gateway的配置文件中,添加Swagger UI的路由映射:
- id: Swagger-UI
uri: lb://swagger-ui
predicates:
- Path=/swagger/**
注意:其中lb://swagger-ui是Swagger UI服务的负载均衡路由名称,例如:
spring:
cloud:
gateway:
routes:
- id: swagger-gateway
uri: http://localhost:8080
predicates:
- Path=/api/**
- id: Swagger-UI
uri: lb://swagger-ui
predicates:
- Path=/swagger/**
discovery:
locator:
lower-case-service-id: true
其中,"Swagger-UI"是对Swagger UI服务名称的定义,在lb://swagger-ui中的"swagger-ui"即为Swagger UI的服务名,需要在服务注册中心中进行注册。
重启API网关后,访问http://api-gateway:8080/swagger-ui.html,即可成功访问Swagger API文档。