SpringCloud网关聚合Swagger接口文档实践( 二 )

四 , 在网关服务中新建SwaggerHandler类:
@RestController@RequestMapping("/swagger-resources")public class SwaggerHandler {@Autowired(required = false)private SecurityConfiguration securityConfiguration;@Autowired(required = false)private UiConfiguration uiConfiguration;private final SwaggerResourcesProvider swaggerResources;@Autowiredpublic SwaggerHandler(SwaggerResourcesProvider swaggerResources) {this.swaggerResources = swaggerResources;}@GetMapping("/configuration/security")public Mono securityConfiguration() {return Mono.just(new ResponseEntity<>(Optional.ofNullable(securityConfiguration).orElse(SecurityConfigurationBuilder.builder().build()), HttpStatus.OK));}@GetMapping("/configuration/ui")public Mono> uiConfiguration() {return Mono.just(new ResponseEntity<>(Optional.ofNullable(uiConfiguration).orElse(UiConfigurationBuilder.builder().build()), HttpStatus.OK));}@GetMapping("")public Mono swaggerResources() {return Mono.just((new ResponseEntity<>(swaggerResources.get(), HttpStatus.OK)));}}
SpringCloud网关聚合Swagger接口文档实践文章插图
五 , SpringCloud后端微服务路由application.yml配置如下:
spring:application:name: sentinel-cloud-gatewaycloud:sentinel:transport:dashboard: localhost:8090eager: trueenabled: truenacos:discovery:server-addr: localhost:8848gateway:enabled: truediscovery:locator:lower-case-service-id: trueroutes:- id: nacos-microservice-orderuri: lb://nacos-microservice-orderpredicates:- Path=/order/**filters:- StripPrefix=1#从前面截取一个 , 实际上就是截取url- id: nacos-microservice-useruri: lb://nacos-microservice-userpredicates:- Path=/user/**filters:- StripPrefix=1#从前面截取一个 , 实际上就是截取urlStripPrefix:从前面截取一个 , 实际上就是截取url , 不然从网关访问聚合swagger会报404错误信息 。
SpringCloud网关聚合Swagger接口文档实践文章插图
六 , 验证
分别启动SpringCloud后端的两个微服务nacos-microservice-order和nacos-microservice-user , 分别访问单个微服务的swagger接口文档
SpringCloud网关聚合Swagger接口文档实践文章插图
验证结果
然后启动sentinel-cloud-gateway网关服务:
SpringCloud网关聚合Swagger接口文档实践文章插图
验证结果
可以看到 , 在微服务的网关服务中聚合了swagger接口文档 , 当后端某个微服务代码发生变更或者代码重构后 , swagger接口文档就会实时更新 , 而且方便测试后端的微服务接口 。
【SpringCloud网关聚合Swagger接口文档实践】不积跬步 , 无以至千里;不积小流 , 无以成江海!