Spring Cloud Gateway 和 Springdoc OpenAPi 整合

3

我成功地将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 中,我期望得到的 URL 是 "http://localhost:8060/students/api/v1/message",但我得到了 "http://localhost:8060/api/v1/message"。
请有心人帮我解决这个问题好吗?谢谢。
1个回答

3

如果您在后面配置了如Spring Cloud Gateway之类的代理应用程序中使用springdoc,则应在服务应用程序中配置此属性:

server.forward-headers-strategy=framework

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

解释:

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

通过设置此属性,您的应用程序将使用这些标头来进行正确的重定向。它会将重定向从/api/v1/message改为/students/api/v1/message(因为x-forwarded-prefix标头中将提供/students前缀)。

只有在所有应用程序的代理都正确配置了这些标头且您信任该代理时才使用此设置。

如果将所有应用程序限制为仅通过Spring Cloud Gateway访问,则可以放心使用。

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接