首页 > 解决方案 > Spring Cloud Gateway 和 Springdoc OpenAPI 集成

问题描述

我能够将 Spring Cloud Gateway 与 Springdoc OpenAPI 集成到一个小型应用程序中,该应用程序具有面向微服务的架构。但是现在,当我打开 Swagger UI 来测试我的控制器 (StudentController) 的端点时,我意识到控制器根级别的 @RequestMapping 不包含在要测试的端点的 URL 中。路由定义如下:

routes:
  - id: students-service
    uri: lb://STUDENTS-SERVICE
    predicates:
      - Path=/students/**
    filters:
      - RewritePath=/students/(?<path>.*), /$\{path}
  - id: openapi
    uri: http://localhost:${server.port}
    predicates:
      - Path=/v3/api-docs/**
    filters:
      - RewritePath=/v3/api-docs/(?<path>.*), /$\{path}/v3/api-docs 

StudentController 如下:

@RestController
@RequestMapping("/api/v1")
@Tag(name = "Students")
public class StudentQueryController {

    @GetMapping("/message")
    public String dummyGet() {
        return "Student Service Dummy GET";
    }
}

在 Swagger UI 中,我希望得到像“http://localhost:8060/students/api/v1/message”这样的 URL,但我得到了“http://localhost:8060/api/v1/message”。

有人会很好地帮助我解决这个问题,好吗?提前致谢。

标签: springcloudopenapigateway

解决方案


如果您在 Spring Cloud Gateway 等代理后面的应用程序中配置了 springdoc,您应该在我们的服务应用程序中配置此属性:

server.forward-headers-strategy=framework

此属性是在 spring-boot 2.2.0 中引入的。

解释:

当请求通过 Spring Cloud Gateway 时,一些与代理相关的 headers 将被添加到请求中(如x-forwarded-hostx-forwarded-proto等)。

设置此属性后,您的应用程序将使用这些标头进行正确的重定向。而不是重定向到/api/v1/message它将重定向到/students/api/v1/message(因为/students前缀将在x-forwarded-prefix标题中可用)。

仅当所有应用程序背后的代理正确配置了这些标头并且您可以信任此代理时,才使用此设置。

如果您将所有应用程序限制为只能通过 Spring Cloud Gateway 访问,那您就可以了。

您可以在此处阅读有关此参数和行为的更多信息。


推荐阅读