spring - 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”。
有人会很好地帮助我解决这个问题,好吗?提前致谢。
解决方案
如果您在 Spring Cloud Gateway 等代理后面的应用程序中配置了 springdoc,您应该在我们的服务应用程序中配置此属性:
server.forward-headers-strategy=framework
此属性是在 spring-boot 2.2.0 中引入的。
解释:
当请求通过 Spring Cloud Gateway 时,一些与代理相关的 headers 将被添加到请求中(如x-forwarded-host
、x-forwarded-proto
等)。
设置此属性后,您的应用程序将使用这些标头进行正确的重定向。而不是重定向到/api/v1/message
它将重定向到/students/api/v1/message
(因为/students
前缀将在x-forwarded-prefix
标题中可用)。
仅当所有应用程序背后的代理正确配置了这些标头并且您可以信任此代理时,才使用此设置。
如果您将所有应用程序限制为只能通过 Spring Cloud Gateway 访问,那您就可以了。
您可以在此处阅读有关此参数和行为的更多信息。
推荐阅读
- python - 尝试使用 for 循环在子图中制作散点图
- javascript - 这个 for in Loop 如何使用 JavaScript 中的快速排序对数字进行排序
- laravel - 我如何避免此错误尝试获取非对象的属性“id”?
- python - Pygame在执行程序后运行缓慢
- python - 如果硒无法找到元素,我如何避免关闭硒
- javascript - 渲染 svgs 并在 React 组件中设置内部 css .this
- c++ - 为什么 pop_back() 在此代码中不起作用?
- linux - iostats 显示逻辑卷的写入次数多于其下的物理卷
- qt - QTCPSocket - 当主机连接到单独的网络时如何强制连接到特定的网络
- java - 这只是一个错字吗?